Ответы пользователя по тегу Python
  • Как сделать ответ на неопознанное сообщение VkBotLongPoll?

    WolfInChains
    @WolfInChains
    import vk_api
    from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
    
    vk = vk_api.VkApi(token="ТОКЕН")
    vk._auth_token()
    vk.get_api()
    longpoll = VkBotLongPoll(vk, АЙДИ ГРУППЫ)
    
    
    def send_msg(peer_id: int, message: str, attachment: str = ""):
        return vk.method("messages.send", {**locals(), "random_id": 0})
    
    while True:
        try:
           for event in longpoll.listen():
               if event.type == VkBotEventType.MESSAGE_NEW:
                   if event.object.peer_id != event.object.from_id: #Для беседы
                       if event.object.text == "Привет":
                           send_msg(event.obj.peer_id, "Пока")
                       else:
                           send_msg(event.obj.peer_id, "Я не знаю такой команды")
                   if event.object.peer_id == event.object.from_id: #Для Лс
                       if event.object.text == "Привет":
                           send_msg(event.obj.peer_id, "Пока")
                       else:
                           send_msg(event.obj.peer_id, "Я не знаю такой команды")
        except Exception as e:
            print(repr(e))
    Ответ написан
    Комментировать
  • Как работать с беседами в вк с помощью бота long poll?

    WolfInChains
    @WolfInChains
    5ec7f1a05a249588232765.pngВыделил капсом места для токена и айди
    import vk_api
    from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
    
    vk = vk_api.VkApi(token="ТОКЕН")
    vk._auth_token()
    vk.get_api()
    longpoll = VkBotLongPoll(vk, АЙДИ ГРУППЫ)
    
    
    def send_msg(peer_id: int, message: str, attachment: str = ""):
        return vk.method("messages.send", {**locals(), "random_id": 0})
    
    while True:
        try:
           for event in longpoll.listen():
               if event.type == VkBotEventType.MESSAGE_NEW:
                   if event.object.peer_id != event.object.from_id: #Для беседы
                       if event.object.text == "Привет":
                           send_msg(event.obj.peer_id, "Пока")
                   if event.object.peer_id == event.object.from_id: #Для Лс
                       if event.object.text == "Привет":
                           send_msg(event.obj.peer_id, "Пока")
        except Exception as e:
            print(repr(e))
    Ответ написан
  • Как не отправлять сообщение, если переменная будет равна 0?

    WolfInChains
    @WolfInChains
    Что-то вроде этого? Если выпал 0, то просто выводит сообщение в консоль, но пользователю не отправляет, если провода, то оправляет сообщение. Капсом обозначил что куда вставлять
    import vk_api
    import random
    from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
    
    vk = vk_api.VkApi(token="ВАШ ТОКЕН")
    vk._auth_token()
    vk.get_api()
    longpoll = VkBotLongPoll(vk, АЙДИ ГРУППЫ) 
    
    
    def send_msg(peer_id: int, message: str, attachment: str = ""):
        return vk.method("messages.send", {**locals(), "random_id": 0})
    
    while True:
        try:
           for event in longpoll.listen():
               if event.type == VkBotEventType.MESSAGE_NEW:
                   if event.object.peer_id == event.object.from_id:   #Только для лс с группой, чтобы работало в беседе == замените на !=
                       if event.object.text == "Рандом":
                           word = "0", "0", "0", "0", 'провода'
                           choice = random.choice(word)
                           if choice == "провода":
                               send_msg(event.obj.peer_id,  f'{choice}')
                           else:
                               print ("Сообщение не отправлено")
        except Exception as e:
            print(repr(e))

    5ec7ecf84e7ff543875675.png5ec7ed0b4f5c4379270149.png
    Ответ написан
    Комментировать
  • Ошибка FileNotFoundError: [Errno 2] No such file or directory. Что не так?

    WolfInChains
    @WolfInChains
    Файла видимо нет в папке.

    И еще вангую ошибку, лучше так
    sti = open('dir/cupwin.webp', 'rb')
    Ответ написан
    Комментировать
  • Не работает bot vk, сможете помочь?

    WolfInChains
    @WolfInChains
    написано же указать айди группы в 12 строке

    Сейчас у вас так
    longpoll = VkBotLongPoll(vk, group_id)

    Должно быть что-то вроде, только вместо 253235626 айди вашей группы
    longpoll = VkBotLongPoll(vk, 253235626)
    Ответ написан
    9 комментариев
  • Telebot: Условные операторы в ReplyKeyboardMarkup?

    WolfInChains
    @WolfInChains
    @bot.message_handler(content_types=['text'])
    def lalala(message):
        if message.chat.type == 'private':
            if message.text == 'album':
    
                markup = types.InlineKeyboardMarkup(row_width=2)
                item1 = types.InlineKeyboardButton("variant1", callback_data='v1')
                item2 = types.InlineKeyboardButton("variant2", callback_data='v2')
    
                markup.add(item1, item2)
    
                bot.send_message(message.chat.id, 'Что имеено интересует', reply_markup=markup)
    
            elif message.text == 'profile':
    
                markup = types.InlineKeyboardMarkup(row_width=2)
                item3 = types.InlineKeyboardButton("variant1", callback_data='v3')
                item4 = types.InlineKeyboardButton("variant2", callback_data='v4')
    
                markup.add(item3, item4)
    
                bot.send_message(message.chat.id, 'Что именно интересует', reply_markup=markup)
    
            elif message.text == 'insta':
    
                markup = types.InlineKeyboardMarkup(row_width=2)
                item5 = types.InlineKeyboardButton("variant1", callback_data='v5')
                item6 = types.InlineKeyboardButton("variant2", callback_data='v6')
    
                markup.add(item5, item6)
    
                bot.send_message(message.chat.id, 'Что именно интересует', reply_markup=markup)
    
            elif message.text == 'facebook':
    
                markup = types.InlineKeyboardMarkup(row_width=2)
                item7 = types.InlineKeyboardButton("variant1", callback_data='v7')
                item8 = types.InlineKeyboardButton("variant2", callback_data='v8')
    
                markup.add(item7, item8)
    
                bot.send_message(message.chat.id, 'Что именно интересует', reply_markup=markup)
    
            elif message.text == 'youtube':
    
                markup = types.InlineKeyboardMarkup(row_width=2)
                item9 = types.InlineKeyboardButton("variant1", callback_data='v9')
                item10 = types.InlineKeyboardButton("variant2", callback_data='v10')
    
                markup.add(item9, item10)
    
                bot.send_message(message.chat.id, 'Что именно интересует', reply_markup=markup)
    
            else:
                bot.send_message(message.chat.id, 'Я не знаю такой команды')
    
    @bot.callback_query_handler(func=lambda call: True)
    def callback_inline(call):
        try:
            if call.message:
                if call.data == 'v1':
                #что должен сделать бот
                elif call.data == 'v2':
                #что должен сделать бот
                #и так далее
        except Exception as e:
         print(repr(e))
    Ответ написан
    Комментировать
  • Как отправить рандомную фотографию из альбома группы с токеном сообщества?

    WolfInChains
    @WolfInChains Автор вопроса
    Решил проблему немного нестандартно, костыль так сказать, но если кому надо, то вот пример
    if event.object.text == "Нами" or event.object.text == "нами":
                           photo_send = random.randint(31, 33)
                           vk.method("messages.send",
                                     {
                                         "chat_id": event.object.peer_id - 2000000000,
                                         "attachment": "photo-193643776_4572390" + f'{photo_send}',
                                         "random_id": random.randint(1, 2147483647)
                                     })

    Открыл первую фотку альбома, скопировал айди фото и стер 2 последние цифры, сделал photo_send = random.randint(31, 33), где 31 и 33- последние 2 цифры айди первой и последней фотки альбома соответсвенно, потом просто добавил полученное значение к айди и все.
    Ответ написан
    Комментировать
  • Как правильно разделить строку?

    WolfInChains
    @WolfInChains Автор вопроса
    Немного подумал и разделил. Если кому надо
    text_1 = event.obj['text'].split(' ', maxsplit=1)
                       if text_1[0] == "Выбери" or text_1[0] == "выбери":
                           text_2 = text_1[1].split('или')
                           list = [text_2[0], text_2[1]]
                           change = random.choice(list)
                           vk.method("messages.send",
                                     {
                                         "chat_id": event.object.peer_id - 2000000000,
                                         "message": "Я выбираю " + f'{change}',
                                         "random_id": random.randint(1, 2147483647)
                                     })
    Ответ написан
    Комментировать
  • Как добавить фразу-ключ по которой будет дан ответ в беседе ВК Апи пайтон?

    WolfInChains
    @WolfInChains
    import vk_api
    import random
    from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
    
    vk = vk_api.VkApi(token="токен")
    vk._auth_token()
    vk.get_api()
    longpoll = VkBotLongPoll(vk, айди группы)
    
    while True:
           for event in longpoll.listen():
               if event.type == VkBotEventType.MESSAGE_NEW:
                   if event.object.peer_id != event.object.from_id:
                       if event.object.text == "пинг"
                            vk.method("messages.send",
                                              {
                                                  "chat_id": event.object.peer_id - 2000000000,
                                                  "message": "понг",
                                                  "random_id": random.randint(1, 2147483647)
                                              }
                                             )
    Ответ написан
    Комментировать