Ejemplo n.º 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
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
    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))
		'''
        '''
Ejemplo n.º 4
0
from bot.handler import (BotButtonCommandHandler, DefaultHandler,
                         HelpCommandHandler, MessageHandler,
                         StartCommandHandler)

import config
from server import (but_deletepost, but_deletepublic, but_post, but_public,
                    but_queuepublic, delete_public, main_message, queue_posts,
                    setpublic_cm, settime_cm, add_post)

bot = Bot(token=config.MAIN_TOKEN)
bot.dispatcher.add_handler(StartCommandHandler(callback=main_message))
bot.dispatcher.add_handler(HelpCommandHandler(callback=main_message))

bot.dispatcher.add_handler(
    MessageHandler(callback=setpublic_cm,
                   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,
Ejemplo n.º 5
0
from bot.filter import Filter
from bot.handler import DefaultHandler, MessageHandler

import config
import database
from event_handler import add_bot, handler_bot, start_info


def start_bots():
    bots = []
    for token in database.get_tokens():
        bot_token = Bot(token=token)
        if bot_token.self_get().json()['ok']:
            bots.append(bot_token)
    for bot in bots:
        bot = handler_bot(bot)
        bot.start_polling()

    
main_bot = Bot(token=config.MAIN_TOKEN)
main_bot.dispatcher.add_handler(MessageHandler(
    callback=add_bot,
    filters=Filter.regexp(r'^/addbot')
))
main_bot.dispatcher.add_handler(DefaultHandler(callback=start_info))
main_bot.start_polling()
start_bots()
main_bot.idle()


Ejemplo n.º 6
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
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")))