コード例 #1
0
def handler_bot(bot):
    bot.dispatcher.add_handler(
        MessageHandler(callback=message_cm,
                       filters=Filter.regexp(r'^/message')))
    bot.dispatcher.add_handler(
        MessageHandler(callback=type_cm, filters=Filter.regexp(r'^/type')))
    bot.dispatcher.add_handler(
        MessageHandler(callback=setchat_cm,
                       filters=Filter.regexp(r'^/setchat')))
    bot.dispatcher.add_handler(
        MessageHandler(callback=ask_cm, filters=Filter.regexp(r'^/ask')))
    bot.dispatcher.add_handler(
        MessageHandler(callback=anon_cm, filters=Filter.regexp(r'^/anon')))
    bot.dispatcher.add_handler(
        MessageHandler(callback=start_cm, filters=Filter.regexp(r'^/start')))
    bot.dispatcher.add_handler(MessageHandler(callback=defauldt_cm))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=but_anon,
                                filters=Filter.callback_data_regexp(r'anon')))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(
            callback=but_public,
            filters=Filter.callback_data_regexp(r'public')))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=but_both,
                                filters=Filter.callback_data_regexp(r'both')))
    return bot
コード例 #2
0
def main():
    bot = Bot(token=TOKEN, name=NAME, version=VERSION)
    bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=buttons_answer_cb))
    bot.start_polling()
    bot.idle()
コード例 #3
0
def main():
    bot.dispatcher.add_handler(BotButtonCommandHandler(callback=answer_cb))
    bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))
    bot.dispatcher.add_handler(
        CommandHandler(command="notwork", callback=notwork_cb))
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.regexp("^(?!/).+"), callback=answer_cb))
    bot.start_polling()
    bot.idle()
コード例 #4
0
def main():
    TOKEN = "001.2422776034.0494128324:752509167"
    bot = Bot(token=TOKEN)

    bot.dispatcher.add_handler(MessageHandler(callback=message_cb))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=buttons_answer_cb))
    bot.dispatcher.add_handler(
        CommandHandler(command="total_rus", callback=get_info_about_russia))

    bot.start_polling()

    bot.idle()
コード例 #5
0
from bot.bot import Bot
from bot.handler import MessageHandler, BotButtonCommandHandler, DefaultHandler
from server import button_processing, message_processing
import config

bot = Bot(token=config.TOKEN)
bot.dispatcher.add_handler(MessageHandler(callback=message_processing))
bot.dispatcher.add_handler(BotButtonCommandHandler(callback=button_processing))
bot.start_polling()
bot.idle()
コード例 #6
0
ファイル: paquebot_bot.py プロジェクト: paje/icq-paquebot
    def __init__(self,
                 token,
                 crew,
                 maindb,
                 api_url_base=None,
                 name=None,
                 version=None,
                 owner=None,
                 timeout_s=20,
                 poll_time_s=60):

        super(Bot, self).__init__()

        self.log = logging.getLogger(__name__)

        self.token = token
        self.api_base_url = "https://api.icq.net/bot/v1" if api_url_base is None else api_url_base
        self.name = name
        self.version = version
        self.owner = owner
        self.timeout_s = timeout_s
        self.poll_time_s = poll_time_s
        self.last_event_id = 0

        self.dispatcher = Dispatcher(self)
        self.running = False

        self._uin = token.split(":")[-1]

        self.__lock = Lock()
        self.__polling_thread = None

        self.__sent_im_cache = ExpiringDict(max_len=2**10, max_age_seconds=60)
        self.dispatcher.add_handler(
            SkipDuplicateMessageHandler(self.__sent_im_cache))

        self.crew = crew
        self.maindb = maindb

        self.parties = parties(self, maindb.paquebot_db)

        resp = self.self_get()
        if resp.status_code == 200:
            myselfinfo = json.loads(resp.text)
            if 'nick' in myselfinfo:
                self.nick = myselfinfo['nick']
            else:
                self.nick = "unknown"
        else:
            self.log.error('Unable to retrive my own infos')

            sys.exit(1)
        self.log.debug('Bot is alive, my ID is %s and my nickname is %s' %
                       (self.uin, self.nick))
        '''
		  Buttons
		'''

        # Handler for bot buttons reply.
        self.dispatcher.add_handler(
            BotButtonCommandHandler(callback=command.answer_buttons))
        '''
		  Commands
		'''

        self.dispatcher.add_handler(
            StartCommandHandler(callback=command.start))

        # Handler for help command
        #self.dispatcher.add_handler(HelpCommandHandler(callback=command.help))
        self.dispatcher.add_handler(
            CommandHandler(command="help", callback=command.help))

        # Start obersing a channel
        self.dispatcher.add_handler(
            CommandHandler(command="joinparty", callback=command.join_party))

        # List managed channels
        self.dispatcher.add_handler(
            CommandHandler(command="listparties",
                           callback=command.list_parties))

        # List managed channels
        self.dispatcher.add_handler(
            CommandHandler(command="setpartylevel",
                           callback=command.set_partyinteraction))
        '''
		# Refresh channel informations (admins, memnbers, blocked, ...)
		self.dispatcher.add_handler(CommandHandler(command="refreshparty", callback=command.refresh_party))
		'''

        # Fix the allowed charsets
        self.dispatcher.add_handler(
            CommandHandler(command="setpartycharsets",
                           callback=command.set_partycharsets))
        '''
		self.dispatcher.add_handler(CommandHandler(command="addpartycharset", callback=command.add_partycharset))
		'''

        # List allowed charsets in a party
        self.dispatcher.add_handler(
            CommandHandler(command="listpartycharsets",
                           callback=command.list_partycharsets))

        # Setting language msg
        self.dispatcher.add_handler(
            CommandHandler(command="setlanguagemsg",
                           callback=command.set_languagemsg))

        # Gettin language msg
        self.dispatcher.add_handler(
            CommandHandler(command="getlanguagemsg",
                           callback=command.get_languagemsg))

        self.dispatcher.add_handler(
            CommandHandler(command="getinfo", callback=command.get_info))

        # List allowed charsets in a party
        self.dispatcher.add_handler(
            CommandHandler(command="listcrew",
                           callback=command.list_crewmembers))
        self.dispatcher.add_handler(
            CommandHandler(command="addcrewmember",
                           callback=command.add_crewmember))
        self.dispatcher.add_handler(
            CommandHandler(command="delcrewmember",
                           callback=command.del_crewmember))

        # Spring cleaning
        self.dispatcher.add_handler(
            CommandHandler(command="springcleaning",
                           callback=command.do_springcleaning))

        # Export/Import
        self.dispatcher.add_handler(
            CommandHandler(command="exportdb", callback=command.do_exportdb))

        self.dispatcher.add_handler(
            CommandHandler(command="importdb", callback=command.do_importdb))

        # Handler for no media file. For example, text file
        self.dispatcher.add_handler(
            MessageHandler(filters=Filter.data, callback=command.receive_file))
        '''
		  non-command handlers
		'''

        # Handler for message with bot mention
        self.dispatcher.add_handler(
            MessageHandler(filters=Filter.message
                           & Filter.mention(user_id=self.uin),
                           callback=command.message_with_bot_mention_cb))

        # Handler for simple text message without text content
        self.dispatcher.add_handler(
            MessageHandler(filters=Filter.text, callback=gunner.watch_txt))
        # same for forward and reply getting
        self.dispatcher.add_handler(
            MessageHandler(filters=Filter.forward, callback=gunner.watch_txt))
        self.dispatcher.add_handler(
            MessageHandler(filters=Filter.reply, callback=gunner.watch_txt))

        # Handler for url
        self.dispatcher.add_handler(
            MessageHandler(filters=Filter.url & ~Filter.sticker,
                           callback=gunner.watch_url))

        # Handler for add user to chat
        self.dispatcher.add_handler(
            NewChatMembersHandler(callback=gunner.do_guestwelcome))

        # Any other user command handler
        #self.dispatcher.add_handler(CommandHandler(command="test", callback=command.test_cb))
        '''
		# Handler for feedback command
		self.dispatcher.add_handler(FeedbackCommandHandler(target=self.owner))
		'''
        '''
		# Handler for unknown commands
		self.dispatcher.add_handler(UnknownCommandHandler(callback=command.unknown_command_cb))
		'''
        '''
		# Handler for private command with filter by user
		self.dispatcher.add_handler(CommandHandler(
			command="restart",
			filters=Filter.sender(user_id=self.owner),
			callback=command.private_command_cb
		))
		'''
        '''
		# Handler for left user from chat
		self.dispatcher.add_handler(LeftChatMembersHandler(callback=command.do_guestgoodbye))
		'''
        '''
		# Handler for pinned message
		self.dispatcher.add_handler(PinnedMessageHandler(callback=command.pinned_message_cb))
		'''
        '''
		# Handler for unpinned message
		self.dispatcher.add_handler(UnPinnedMessageHandler(callback=command.unpinned_message_cb))
		'''
        '''
		# Handler for edited message
		bot.dispatcher.add_handler(EditedMessageHandler(callback=c.edited_message_cb))
		'''
        '''
		# Handler for deleted message
		self.dispatcher.add_handler(DeletedMessageHandler(callback=command.deleted_message_cb))
		'''
        '''
		# Handler for mention something else
		self.dispatcher.add_handler(MessageHandler(
			filters=Filter.mention() & ~Filter.mention(user_id=self.uin),
			callback=command.mention_cb
		))
		'''

        # Handler with regexp filter
        #self.dispatcher.add_handler(MessageHandler(filters=Filter.regexp("^\d*$"), callback=command.regexp_only_dig_cb))
        '''


		'''
        '''
		# Handlers for other file types
		self.dispatcher.add_handler(MessageHandler(filters=Filter.image, callback=command.image_cb))
		self.dispatcher.add_handler(MessageHandler(filters=Filter.video, callback=command.video_cb))
		self.dispatcher.add_handler(MessageHandler(filters=Filter.audio, callback=command.audio_cb))
		'''
        '''
		# Handler for sticker
		self.dispatcher.add_handler(MessageHandler(filters=Filter.sticker, callback=command.sticker_cb))
		'''
        '''
		# Handler for url
		self.dispatcher.add_handler(MessageHandler(filters=Filter.url & ~Filter.sticker, callback=command.url_cb))
		'''
        '''		
		# Handlers for forward and reply getting
		self.dispatcher.add_handler(MessageHandler(filters=Filter.forward, callback=command.forward_cb))
		self.dispatcher.add_handler(MessageHandler(filters=Filter.reply, callback=command.reply_cb))
		'''

        # Send command like this:
        # /pin 6752793278973351456
        # 6752793278973351456 - msgId
        # Handler for pin command
        # self.dispatcher.add_handler(CommandHandler(command="pin", callback=command.pin_cb))

        # Send command like this:
        # /unpin 6752793278973351456
        # 6752793278973351456 - msgId
        # Handler for unpin command
        # self.dispatcher.add_handler(CommandHandler(command="unpin", callback=command.unpin_cb))
        '''
		# List available charsets
		self.dispatcher.add_handler(CommandHandler(command="listcharsets", callback=command.list_charsets))
		'''
        '''
コード例 #7
0
ファイル: delay_bot.py プロジェクト: ICQ-BOTS/delay_bot
                   filters=Filter.regexp(r'^\/setpublic')))

bot.dispatcher.add_handler(
    MessageHandler(callback=settime_cm, filters=Filter.regexp(r'^\/settime')))

bot.dispatcher.add_handler(
    MessageHandler(callback=delete_public,
                   filters=Filter.regexp(r'^\/delete')))

bot.dispatcher.add_handler(
    MessageHandler(callback=queue_posts, filters=Filter.regexp(r'^\/queue')))

bot.dispatcher.add_handler(DefaultHandler(callback=add_post))

bot.dispatcher.add_handler(
    BotButtonCommandHandler(callback=but_public,
                            filters=Filter.callback_data_regexp(r'public')))

bot.dispatcher.add_handler(
    BotButtonCommandHandler(callback=but_post,
                            filters=Filter.callback_data_regexp(r'post')))

bot.dispatcher.add_handler(
    BotButtonCommandHandler(
        callback=but_deletepublic,
        filters=Filter.callback_data_regexp(r'deletepublic')))

bot.dispatcher.add_handler(
    BotButtonCommandHandler(
        callback=but_deletepost,
        filters=Filter.callback_data_regexp(r'deletepost')))
コード例 #8
0
    if len(file_ids) == 0:
        bot.send_text(chat_id=event.from_chat, text='Необходимо загрузить один файл!')
    elif len(file_ids) > 1:
        bot.send_text(chat_id=event.from_chat, text='Мы умеем обрабатывать только один докумнет!')
    else:
        ans = bot.get_file_info(file_id=file_ids[0])
        file_type = json.loads(ans.text)['filename'].split('.')[-1]
        if file_type == 'pdf':
            bot.send_text(chat_id=event.from_chat,
                    text = 
                    """Что нужно сделать с документом? \n 1 - Извлечь изображения \n 2 - Извлечь таблицы \n 3 - Извлечь текст \n 4 - Преобразовать в docx-формат""",
                    inline_keyboard_markup="{}".format(json.dumps([[
                        {"text": "1", "callbackData": f"call_back_id_1@{event.from_chat}@{file_ids[0]}", "style": "primary"},
                        {"text": "2", "callbackData": f"call_back_id_2@{event.from_chat}@{file_ids[0]}", "style": "primary"},
                        {"text": "3", "callbackData": f"call_back_id_3@{event.from_chat}@{file_ids[0]}", "style": "primary"},
                        {"text": "4", "callbackData": f"call_back_id_4@{event.from_chat}@{file_ids[0]}", "style": "primary"}
                    ]])))
        else:
            bot.send_text(chat_id=event.from_chat, text='Ошибка формата! Загрузите, пожалуйста, PDF!')


def start_cb(bot, event):
    bot.send_text(chat_id=event.data['chat']['chatId'], text="Добрый день!\nМы поможем вам в работе с PDF-документами.\nДля начала работы отправьте один PDF-документ боту.")


bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))
bot.dispatcher.add_handler(MessageHandler(filters=Filter.text, callback=message_cb_text))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb))
bot.dispatcher.add_handler(BotButtonCommandHandler(callback=buttons_answer_cb))
bot.start_polling()
bot.idle()
コード例 #9
0
                    "url": "https://www.delivery-club.ru/"
                },
                {
                    "text": "5",
                    "url": "https://wf.mail.ru/"
                },
                {
                    "text": "6",
                    "url": "https://www.youtube.com/"
                },
            ]])))


bot.dispatcher.add_handler(HelpCommandHandler(callback=help_cb))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb))
bot.dispatcher.add_handler(
    MessageHandler(filters=Filter.image, callback=image_cb))
bot.dispatcher.add_handler(CommandHandler(command='start', callback=start_mes))
bot.dispatcher.add_handler(
    CommandHandler(command='game', callback=mygame_mygame_bastaakanagana))
bot.dispatcher.add_handler(CommandHandler(command='gettest',
                                          callback=runTests))
bot.dispatcher.add_handler(
    CommandHandler(command='recommend', callback=recommendation))
bot.dispatcher.add_handler(BotButtonCommandHandler(callback=testcommands))
bot.dispatcher.add_handler(CommandHandler(command='info', callback=stat))
bot.dispatcher.add_handler(CommandHandler(command='getfun', callback=getfun))
bot.dispatcher.add_handler(UnknownCommandHandler(callback=UnknownCommand))

bot.start_polling()
bot.idle()
コード例 #10
0
    while first_index == 1 and second_index == 1:
        first_index = random.randrange(2)
        second_index = random.randrange(2)
    if first_index == second_index:
        first_action = random.choice(actions[first_index])
        second_action = first_action.copy()
        while first_action[0]['text'] == second_action[0]['text']:
            second_action = random.choice(actions[second_index])
    else:
        first_action = random.choice(actions[first_index])
        second_action = random.choice(actions[second_index])
    return [first_action, second_action]


def get_rand_actions():
    first_action = random.choice(actions[0])
    second_action = random.choice(actions[1])
    res = random.choice(
        list(itertools.permutations([first_action, second_action])))
    print('random: ')
    print(first_action, second_action)
    print(res)
    print('end random')
    return list(res)


bot.dispatcher.add_handler(MessageHandler(callback=message_cb))
bot.dispatcher.add_handler(BotButtonCommandHandler(callback=query_cb))
bot.start_polling()
idle.our_idle()
コード例 #11
0
 def register(self, filters=None, command: str = None):
     self._dp.add_handler(BotButtonCommandHandler(callback=self.execute))
コード例 #12
0
def main():
    # Creating a new bot instance.
    bot = Bot(token=TOKEN, name=NAME, version=VERSION, api_url_base=API_URL)

    # Registering handlers #
    # -------------------- #
    # Handler for start command
    bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))

    # Handler for help command
    bot.dispatcher.add_handler(HelpCommandHandler(callback=help_cb))

    # Any other user command handler
    bot.dispatcher.add_handler(CommandHandler(command="test",
                                              callback=test_cb))

    # Handler for feedback command
    bot.dispatcher.add_handler(FeedbackCommandHandler(target=OWNER))

    # Handler for unknown commands
    bot.dispatcher.add_handler(
        UnknownCommandHandler(callback=unknown_command_cb))

    # Handler for private command with filter by user
    bot.dispatcher.add_handler(
        CommandHandler(command="restart",
                       filters=Filter.sender(user_id=OWNER),
                       callback=private_command_cb))

    # Handler for add user to chat
    bot.dispatcher.add_handler(
        NewChatMembersHandler(callback=new_chat_members_cb))

    # Handler for left user from chat
    bot.dispatcher.add_handler(
        LeftChatMembersHandler(callback=left_chat_members_cb))

    # Handler for pinned message
    bot.dispatcher.add_handler(
        PinnedMessageHandler(callback=pinned_message_cb))

    # Handler for unpinned message
    bot.dispatcher.add_handler(
        UnPinnedMessageHandler(callback=unpinned_message_cb))

    # Handler for edited message
    bot.dispatcher.add_handler(
        EditedMessageHandler(callback=edited_message_cb))

    # Handler for deleted message
    bot.dispatcher.add_handler(
        DeletedMessageHandler(callback=deleted_message_cb))

    # Handler for message with bot mention
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.message
                       & Filter.mention(user_id=bot.uin),
                       callback=message_with_bot_mention_cb))

    # Handler for mention something else
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.mention()
                       & ~Filter.mention(user_id=bot.uin),
                       callback=mention_cb))

    # Handler for simple text message without media content
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.text, callback=message_cb))

    # Handler with regexp filter
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.regexp("^\d*$"),
                       callback=regexp_only_dig_cb))

    # Handler for no media file. For example, text file
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.data, callback=file_cb))

    # Handlers for other file types
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.image, callback=image_cb))
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.video, callback=video_cb))
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.audio, callback=audio_cb))

    # Handler for sticker
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.sticker, callback=sticker_cb))

    # Handler for url
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.url & ~Filter.sticker, callback=url_cb))

    # Handlers for forward and reply getting
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.forward, callback=forward_cb))
    bot.dispatcher.add_handler(
        MessageHandler(filters=Filter.reply, callback=reply_cb))

    # Send command like this:
    # /pin 6752793278973351456
    # 6752793278973351456 - msgId
    # Handler for pin command
    bot.dispatcher.add_handler(CommandHandler(command="pin", callback=pin_cb))

    # Send command like this:
    # /unpin 6752793278973351456
    # 6752793278973351456 - msgId
    # Handler for unpin command
    bot.dispatcher.add_handler(
        CommandHandler(command="unpin", callback=unpin_cb))

    # Starting a polling thread watching for new events from server. This is a non-blocking call
    # ---------------------------------------------------------------------------------------- #
    bot.start_polling()

    # Call bot methods
    # -------------- #
    # Get info about bot
    bot.self_get()

    # Send message
    response = bot.send_text(chat_id=OWNER, text="Hello")
    msg_id = response.json()['msgId']

    # Reply
    bot.send_text(chat_id=OWNER, text="Reply to 'Hello'", reply_msg_id=msg_id)

    # Forward
    bot.send_text(chat_id=OWNER,
                  text="Forward 'Hello'",
                  forward_msg_id=msg_id,
                  forward_chat_id=OWNER)

    # Send binary file
    with io.StringIO() as file:
        file.write(u'x' * 100)
        file.name = "file.txt"
        file.seek(0)
        response = bot.send_file(chat_id=OWNER,
                                 file=file.read(),
                                 caption="binary file caption")
        file_id = response.json()['fileId']

    # Get file info
    bot.get_file_info(file_id=file_id)

    # Send file by file_id
    bot.send_file(chat_id=OWNER,
                  file_id=file_id,
                  caption="file_id file caption")

    # Send file by file_id as reply to message
    bot.send_file(chat_id=OWNER,
                  file_id=file_id,
                  caption="file_id file caption",
                  reply_msg_id=msg_id)

    # Forward file by file_id
    bot.send_file(chat_id=OWNER,
                  file_id=file_id,
                  caption="file_id file caption",
                  forward_msg_id=msg_id,
                  forward_chat_id=OWNER)

    # Send voice file
    if sys.version_info[0] == 3:
        with io.BytesIO() as file:
            gTTS('Hello everybody!').write_to_fp(file)
            file.name = "hello_voice.mp3"
            file.seek(0)
            response = bot.send_voice(chat_id=OWNER, file=file.read())
            hello_voice_file_id = response.json()['fileId']

        # Send voice by file_id
        bot.send_voice(chat_id=OWNER, file_id=hello_voice_file_id)

    # Edit text
    msg_id = bot.send_text(chat_id=OWNER,
                           text="Message to be edited").json()['msgId']
    bot.edit_text(chat_id=OWNER, msg_id=msg_id, text="edited text")

    # Delete message
    msg_id = bot.send_text(chat_id=OWNER,
                           text="Message to be deleted").json()['msgId']
    bot.delete_messages(chat_id=OWNER, msg_id=msg_id)

    # Send typing action
    bot.send_actions(chat_id=OWNER, actions=["typing"])
    sleep(1)
    # Stop typing
    bot.send_actions(chat_id=OWNER, actions=[])

    # Get info about chat
    bot.get_chat_info(chat_id=TEST_CHAT)

    # Get chat admins
    bot.get_chat_admins(chat_id=TEST_CHAT)
    # Get chat members
    bot.get_chat_members(chat_id=TEST_CHAT)
    # Get chat blocked users
    bot.get_chat_blocked_users(chat_id=TEST_CHAT)
    # Get chat pending users
    bot.get_chat_pending_users(chat_id=TEST_CHAT)

    # Block user in chat
    bot.chat_block_user(chat_id=TEST_CHAT,
                        user_id=TEST_USER,
                        del_last_messages=True)
    # Unlock user in chat
    bot.chat_unblock_user(chat_id=TEST_CHAT, user_id=TEST_USER)

    # Chat resolve pending user or everyone
    bot.chat_resolve_pending(chat_id=TEST_CHAT,
                             approve=True,
                             user_id=TEST_USER,
                             everyone=False)

    # Set chat title
    bot.set_chat_title(chat_id=TEST_CHAT, title="TEST TITLE")
    # Set chat about
    bot.set_chat_about(chat_id=TEST_CHAT, about="TEST ABOUT")
    # Set chat title
    bot.set_chat_rules(chat_id=TEST_CHAT, rules="TEST RULES")

    # Send bot buttons
    bot.send_text(chat_id=OWNER,
                  text="Hello with buttons.",
                  inline_keyboard_markup="[{}]".format(
                      json.dumps([{
                          "text": "Action 1",
                          "url": "http://mail.ru"
                      }, {
                          "text": "Action 2",
                          "callbackData": "call_back_id_2"
                      }, {
                          "text": "Action 3",
                          "callbackData": "call_back_id_3"
                      }])))

    # Handler for bot buttons reply.
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=buttons_answer_cb))

    bot.idle()
コード例 #13
0
            title[10].get_text(strip=True) + " -" + "промокод: " +
            code[10].get_text(strip=True))


def message_cb_start(bot, event):
    if event.text[0:6] == "/start":
        bot.send_text(
            chat_id=event.from_chat,
            text=
            "Приветствую тебя, мой друг! Я бот-помощник. Я с радостью помогу тебе решить множество проблем. С помощью меня ты сможешь найти различные организации, узнать погоду, новости и многое другое! Напиши  /help для ознакомления со всеми моими командами. Удачного использования!"
        )


bot.dispatcher.add_handler(MessageHandler(callback=message_cb_start))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_code))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_rate))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_coronavirus))
bot.dispatcher.add_handler(
    BotButtonCommandHandler(callback=buttons_answer_cb_coronavirus))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_find))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_weather))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_news))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_search))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_coin))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_to_rus))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_to_eng))
bot.dispatcher.add_handler(MessageHandler(callback=message_cb_serials))

bot.start_polling()
bot.idle()
コード例 #14
0
def main():
    # создаем инстанс бота
    bot = Bot(token=TOKEN, name=NAME, version=VERSION, api_url_base=API_URL)

    # Регистрация хэндлеров #
    # -------------------- #
    # Хэндлер для команды /start
    bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))

    # Хэндлер для команды /help
    bot.dispatcher.add_handler(HelpCommandHandler(callback=help_cb))

    # Хэндлер для пользовательской команды /test
    bot.dispatcher.add_handler(CommandHandler(command="test", callback=test_cb))

    # Хэндлер для фидбэка
    bot.dispatcher.add_handler(FeedbackCommandHandler(target=OWNER))

    # Хэндлер для неправильной команды
    bot.dispatcher.add_handler(UnknownCommandHandler(callback=unknown_command_cb))

    # Хэндлер для приватной команды с фильтром по отправителю (сработает только при отправке команды разработчиком бота)
    bot.dispatcher.add_handler(CommandHandler(
        command="restart",
        filters=Filter.sender(user_id=OWNER),
        callback=private_command_cb
    ))

    # Хэндлер для команды "Новый пользователь"
    bot.dispatcher.add_handler(NewChatMembersHandler(callback=new_chat_members_cb))

    # Хэндлер для команды "Пользователь покинул группу"
    bot.dispatcher.add_handler(LeftChatMembersHandler(callback=left_chat_members_cb))

    # Хэндлер для команды "Сообщение закреплено"
    bot.dispatcher.add_handler(PinnedMessageHandler(callback=pinned_message_cb))

    # Хэндлер для команды "Сообщение откреплено"
    bot.dispatcher.add_handler(UnPinnedMessageHandler(callback=unpinned_message_cb))

    # Хэндлер для редактирования сообщения
    bot.dispatcher.add_handler(EditedMessageHandler(callback=edited_message_cb))

    # Хэндлер для удаления сообщения (ОТКЛЮЧЕН, НЕ ИСПОЛЬЗОВАТЬ)
    bot.dispatcher.add_handler(DeletedMessageHandler(callback=deleted_message_cb))

    # Хэндлер для упоминания ботом
    bot.dispatcher.add_handler(MessageHandler(
        filters=Filter.message & Filter.mention(user_id=bot.uin),
        callback=message_with_bot_mention_cb
    ))

    # Хэндлер для упоминания пользователем
    bot.dispatcher.add_handler(MessageHandler(
        filters=Filter.mention() & ~Filter.mention(user_id=bot.uin),
        callback=mention_cb
    ))

    # Хэндлер для текста без файлов
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.text, callback=message_cb))

    # Хэндлер с регулярным выражением: только цифры
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.regexp("^\d*$"), callback=regexp_only_dig_cb))

    # Хэндлер для немедийного файла (например, MarkFomin.txt)
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.data, callback=file_cb))

    # Handlers for other file types
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.image, callback=image_cb))
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.video, callback=video_cb))
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.audio, callback=audio_cb))

    # Хэндлер для стикера
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.sticker, callback=sticker_cb))

    # Хэндлер для ссылки
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.url & ~Filter.sticker, callback=url_cb))

    # Хэндлеры для пересылания и ответа на сообщение соответственно
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.forward, callback=forward_cb))
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.reply, callback=reply_cb))

    # Команда /pin закрепляет сообщение по его msgId:
    # /pin 6752793278973351456
    # 6752793278973351456 - msgId
    # Хэндлер для команды
    bot.dispatcher.add_handler(CommandHandler(command="pin", callback=pin_cb))

    # Команда /unpin открепляет сообщение по его msgId:
    # /unpin 6752793278973351456
    # 6752793278973351456 - msgId
    # Хэндлер для команды
    bot.dispatcher.add_handler(CommandHandler(command="unpin", callback=unpin_cb))

    # Запускаем получение событий с сервера ICQ
    # ---------------------------------------------------------------------------------------- #
    bot.start_polling()

    # Методы, которые можно использовать в библиотеке:
    # -------------- #
    # Информация о боте
    bot.self_get()

    # Отправка сообщений
    response = bot.send_text(chat_id=OWNER, text="Привет")
    msg_id = response.json()['msgId']

    # Ответ на сообщение
    bot.send_text(chat_id=OWNER, text="Ответ на 'Привет'", reply_msg_id=msg_id)

    # Переслать сообщение
    bot.send_text(chat_id=OWNER, text="Пересылаю 'Привет'", forward_msg_id=msg_id, forward_chat_id=OWNER)

    # отправка файла
    with io.StringIO() as file:
        file.write(u'x'*100)
        file.name = "file.txt"
        file.seek(0)
        response = bot.send_file(chat_id=OWNER, file=file.read(), caption="binary file caption")
        file_id = response.json()['fileId']

    # Инофрмация об отправленном файле
    bot.get_file_info(file_id=file_id)

    # Повторно отправить файл
    bot.send_file(chat_id=OWNER, file_id=file_id, caption="file_id file caption")

    # Также можно отправить повторно файл ответом на сообщение
    bot.send_file(chat_id=OWNER, file_id=file_id, caption="file_id file caption", reply_msg_id=msg_id)

    # Переслать файл по его идентификатору
    bot.send_file(
        chat_id=OWNER,
        file_id=file_id,
        caption="file_id file caption",
        forward_msg_id=msg_id,
        forward_chat_id=OWNER
    )

    # Отправить TTS файл
    if sys.version_info[0] == 3:
        with io.BytesIO() as file:
            gTTS('Перевод выполнен Марком Фоминым в 2021 году.').write_to_fp(file)
            file.name = "hello_voice.mp3"
            file.seek(0)
            response = bot.send_voice(chat_id=OWNER, file=file.read())
            hello_voice_file_id = response.json()['fileId']

        # Отправка файла POST-запросом по его идентификатору
        bot.send_voice(chat_id=OWNER, file_id=hello_voice_file_id)

    # Редактирование текста, уже отправленного ботом
    msg_id = bot.send_text(chat_id=OWNER, text="Это сообщение будет отредактировано").json()['msgId']
    bot.edit_text(chat_id=OWNER, msg_id=msg_id, text="Все, его уже отредактировали.")

    # Удалить сообщение пользователя
    msg_id = bot.send_text(chat_id=OWNER, text="Сообщение будет удалено.").json()['msgId']
    bot.delete_messages(chat_id=OWNER, msg_id=msg_id)

    # Пусть бот будет печатать в течение 1 секунды
    bot.send_actions(chat_id=OWNER, actions=["typing"])
    sleep(1)
    # Пусть бот перестанет печатать
    bot.send_actions(chat_id=OWNER, actions=[])

    # Информация о чате
    bot.get_chat_info(chat_id=TEST_CHAT)

    # Получить список админов чата
    bot.get_chat_admins(chat_id=TEST_CHAT)
    # Поулчить список участников чата
    bot.get_chat_members(chat_id=TEST_CHAT)
    # Получить список удаленных участников
    bot.get_chat_blocked_users(chat_id=TEST_CHAT)
    # Получить список ожидающих подтверждения на вход
    bot.get_chat_pending_users(chat_id=TEST_CHAT)

    # Заблокировать пользователя в чате
    bot.chat_block_user(chat_id=TEST_CHAT, user_id=TEST_USER, del_last_messages=True)
    # Разблокировать пользователя в чате
    bot.chat_unblock_user(chat_id=TEST_CHAT, user_id=TEST_USER)

    # Принять решение о подтверждении/отклонении заявки на вход в группу
    bot.chat_resolve_pending(chat_id=TEST_CHAT, approve=True, user_id=TEST_USER, everyone=False)

    # Установить название чата
    bot.set_chat_title(chat_id=TEST_CHAT, title="Захват мира")
    # Установить инофрмацию о группе
    bot.set_chat_about(chat_id=TEST_CHAT, about="Группа для душевного общения.")
    # Установить правила группы
    bot.set_chat_rules(chat_id=TEST_CHAT, rules="Не ругайтесь матом и не обзывайте участников чата!)")

    # Отправить сообщение с кнопками
    bot.send_text(chat_id=OWNER,
                  text="Привет, я сообщение с кнопками!",
                  inline_keyboard_markup="[{}]".format(json.dumps([
                      {"text": "Кнопка 1", "url": "https://vk.com/na_official/"},
                      {"text": "Кнопка 2", "callbackData": "call_back_id_2"},
                      {"text": "Кнопка 3", "callbackData": "call_back_id_3"}
                  ])))
    '''
    url - используется для ссылки, не может быть передано одновременно с callbackData;
    callbackData - используется для обработки нажатия кнопки
    '''

    # Хэндлер для обработки нажатия кнопки
    bot.dispatcher.add_handler(BotButtonCommandHandler(callback=buttons_answer_cb))

    bot.idle()
コード例 #15
0
def launch_handlers(bot):
    bot.dispatcher.add_handler(MessageHandler(callback=get_answer_by_text))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=types,
                                filters=Filter.callback_data("types")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=callbacks_with_all_prefix,
                                filters=Filter.callback_data_regexp("all.*")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=rand,
                                filters=Filter.callback_data("rand")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=newline,
                                filters=Filter.callback_data("newline")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=custom_intro,
                                filters=Filter.callback_data("custom_intro")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=styles,
                                filters=Filter.callback_data("styles")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=nothing,
                                filters=Filter.callback_data("nothing")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=toast,
                                filters=Filter.callback_data("toast")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=alert,
                                filters=Filter.callback_data("alert")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=url,
                                filters=Filter.callback_data("url")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=alert_url,
                                filters=Filter.callback_data("alert_url")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=toast_url,
                                filters=Filter.callback_data("toast_url")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=edit,
                                filters=Filter.callback_data("edit")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=edit_intro,
                                filters=Filter.callback_data("edit_intro")))
    bot.dispatcher.add_handler(
        BotButtonCommandHandler(callback=small_buttons,
                                filters=Filter.callback_data("micro_buttons")))