Помощь с библиотекой vk_api(бот вк)
Нужна помощь, дело в том, что бот отвечает в лс, но никак не хочет в беседе, пробовал многое, не получается. Рад буду любым доводам. P.S Бот в беседы состоит, выданы все необходимые права доступа.
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
import calendar
import random
import string
import whois
import phonenumbers
from phonenumbers import carrier, geocoder
token = "УКАЗАН"
di = vk_api.VkApi(token=token)
give = di.get_api()
longpoll = VkLongPoll(di)
def __sendMeesage(id, text):
di.method('messages.send', {'user_id': id, 'message': text, 'random_id': 0})
for event in longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW:
if event.to_me:
message = event.text.lower()
id = event.user_id
# The function is a calendar. It does not work correctly, the code should be slightly tweaked.
if message == '/calendar':
__sendMeesage(id, calendar.month(2021, 8))
# Generating a random password. If necessary, you can supplement the code.
elif message == '/password':
a = string.ascii_letters + string.digits
b = ''.join(random.choice(a) for i in range(8))
__sendMeesage(id, f'You random password: {b}')
# Function - domain name check. Displays brief information about the domain. The code should be added.
elif message == '/domain':
domain = 'google.com'
domain_info = whois.whois(domain)
for key, value in domain_info.items():
# print(key, ':', value)
__sendMeesage(id, f'{key} : {value}')
#Function - brief information about the mobile phone number. Displays short info. by phone number.
# Not completed yet.
elif message == '/phone':
a = phonenumbers.parse('+71234567890')
__sendMeesage(id, f'Country - {geocoder.description_for_number(a, "ru")}')
__sendMeesage(id, f'Mobile operator - {carrier.name_for_number(a, "ru")}')
__sendMeesage(id, f'❗ The function was created in test mode and will be added in the future. ❗')
else:
__sendMeesage(id, '❗ I don`t speaking you! :( ❗ \n ?⛔ My functionality: ?⛔ \n ⛔ /calendar ⛔ \n '
'⛔ /password ⛔ \n ⛔/domain ⛔ \n ⛔ /phone ⛔')
Ответы (2 шт):
Попробуй написать if event.type == VkEventType.MESSAGE_NEW and event.from_chat
Ну, во-первых, указывая только условие event.to_me, не создавая внутри разделы: event.from_user и event.from_chat, бот будет отвечать везде, только вот в чём Ваша ошибка:
if event.to_me:
message = event.text.lower()
id = event.user_id
# Код ответов
Здесь Вы узнаете только id пользователя, и бот не сможет написать в беседу, не зная её id.
Добавьте после получения id пользователя - chat_id = event.chat_id
Теперь у Вас есть id беседы.
Идём дальше:
def __sendMeesage(id, text):
di.method('messages.send', {'user_id': id, 'message': text, 'random_id': 0})
Здесь указан метод только на ответ в лс. Добавим в аттрибуты переменную, при получении которой, будем отправлять в беседу. Вот пример кода:
def __sendMeesage(id, text, chat=False):
if chat == False: # Если False
di.method('messages.send', {'user_id': id, 'message': text, 'random_id': 0})
elif chat == True: # Если True
di.method('messages.send', {'chat_id': id, 'message': text, 'random_id': 0})
Готово, теперь при указании: __sendMeesage(chat_id, text, True) - текст отправится в беседу.
А при указании: __sendMeesage(id, text) - текст отправится в лс.
Едем дальше. Возьмём для примера функцию календаря:
if message == '/calendar':
__sendMeesage(id, calendar.month(2021, 8))
Здесь у Вас так и указывается: отправить в лс. Давайте это исправим:
if message == '/calendar':
if event.from_user: # Если нам написали в лс, то всё - то же самое
__sendMeesage(id, calendar.month(2021, 8))
elif event.from_chat: # Если нам написали в беседу
__sendMeesage(chat_id, calendar.month(2021, 8), True) # Здесь указываем chat_id и в конце True, чтобы отправилось в беседу.
Готово! Надеюсь, я смог Вам помочь