예제 #1
0
    def test_basic(self, dp, message):
        handler = MessageHandler(None, self.callback_basic)
        dp.add_handler(handler)

        assert handler.check_update(Update(0, message))
        dp.process_update(Update(0, message))
        assert self.test_flag
예제 #2
0
    def test_with_filter(self, message):
        handler = MessageHandler(Filters.command, self.callback_basic)

        message.text = '/test'
        assert handler.check_update(Update(0, message))

        message.text = 'test'
        assert not handler.check_update(Update(0, message))
예제 #3
0
    def test_channel_post(self, message):
        handler = MessageHandler(None, self.callback_basic, edited_updates=False,
                                 message_updates=False, channel_post_updates=True)

        assert not handler.check_update(Update(0, edited_message=message))
        assert not handler.check_update(Update(0, message=message))
        assert handler.check_update(Update(0, channel_post=message))
        assert not handler.check_update(Update(0, edited_channel_post=message))
예제 #4
0
    def test_allow_edited(self, message):
        with pytest.warns(UserWarning):
            handler = MessageHandler(None, self.callback_basic, message_updates=True,
                                     allow_edited=True, channel_post_updates=False)

        assert handler.check_update(Update(0, edited_message=message))
        assert handler.check_update(Update(0, message=message))
        assert not handler.check_update(Update(0, channel_post=message))
        assert handler.check_update(Update(0, edited_channel_post=message))
예제 #5
0
def runbot():
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    my_persistence = PicklePersistence(filename='data.pickle')

    updater = Updater(TOKEN, persistence=my_persistence, use_context=True)


    job = updater.job_queue

    def check_new_month(context):
        if (datetime.datetime.today().day == 1):
            file_Name = "data.pickle"
            # we open the file for reading
            fileObject = open(file_Name,'rb')  
            # load the object from the file into var b
            b = pickle.load(fileObject)  

            for k, v in b['user_data'].items():
                if (v['tableid']): 
                    currentMonth = time.strftime("%m.%y", time.localtime())
                    
                    if( createBlankSheet(v['tableid'], currentMonth) ):
                        initSheet(context, k, v['tableid'])
                        context.bot.send_message(chat_id=k, 
                            text='Поздравляем с наступлением нового месяца! Новая таблица была создана автоматически.')

    job_check_new_month = job.run_daily(check_new_month, datetime.time(0,0,1))



    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states CHOOSING, TYPING_CATEGORY and TYPING_REPLY
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        states={
            CHOOSING: [MessageHandler(Filters.regex('^(Добавить расходы|Добавить доход|Добавить уникальную покупку/услугу|Добавить уникальный доход)$'),
                                      add_money),
                       MessageHandler(Filters.regex('^(Добавить новую категорию|Добавить категорию расходов|Добавить категорию доходов)$'),
                                      add_new_category),
                       MessageHandler(Filters.text,
                                      received_category)
                       ],

            TYPING_AMOUNT: [MessageHandler(Filters.text,
                                           received_amount),
                            ],

            TYPING_CATEGORY: [MessageHandler(Filters.text,
                                             received_category)
                              ],

            TYPING_NEW_CATEGORY: [MessageHandler(Filters.text,
                                                 received_new_category)
                                  ],
            ADDING_TABLE: [MessageHandler(Filters.text,
                                                 add_new_table)
                                    ],
        },
        fallbacks=[
            CommandHandler('newtable', newtable)
        ],
        name="MainConv",
        persistent=True
    )


    dp.add_handler(conv_handler)

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
예제 #6
0
 - /locks: The current list of locks in this chat.
 
Locks can be used to restrict a group's users.
eg:
Locking urls will auto-delete all messages with urls, locking stickers will restrict all \
non-admin users from sending stickers, etc.
Locking bots will stop non-admins from adding bots to the chat.

Note:
 • Unlocking permission *info* will allow members (non-admins) to change the group information, such as the description or the group name
 • Unlocking permission *pin* will allow members (non-admins) to pinned a message in a group
"""

__mod_name__ = "Locks"

LOCKTYPES_HANDLER = DisableAbleCommandHandler("locktypes", locktypes)
LOCK_HANDLER = CommandHandler("lock", lock, pass_args=True)  # , filters=Filters.group)
UNLOCK_HANDLER = CommandHandler(
    "unlock", unlock, pass_args=True
)  # , filters=Filters.group)
LOCKED_HANDLER = CommandHandler("locks", list_locks)  # , filters=Filters.group)

dispatcher.add_handler(LOCK_HANDLER)
dispatcher.add_handler(UNLOCK_HANDLER)
dispatcher.add_handler(LOCKTYPES_HANDLER)
dispatcher.add_handler(LOCKED_HANDLER)

dispatcher.add_handler(
    MessageHandler(Filters.all & Filters.group, del_lockables), PERM_GROUP
)
예제 #7
0
def main():
    """
    The entrypoint for omnbot-frontend. The main function adds all handlers to the telegram dispatcher, informs the
    admin about the startup and runs the dispatcher forever.
    """
    global frontend_fh
    global message_fh
    global cache

    frontend_fh = logging.handlers.TimedRotatingFileHandler('logs/frontend.log', when='midnight', backupCount=60)
    frontend_fh.setLevel(logging.DEBUG)
    frontend_fh.setFormatter(formatter)
    frontend_logger.addHandler(frontend_fh)

    message_fh = logging.handlers.TimedRotatingFileHandler('logs/messages.log', when='midnight', backupCount=60)
    message_fh.setLevel(logging.DEBUG)
    message_fh.setFormatter(formatter)
    message_logger.addHandler(message_fh)

    redis_host = os.environ.get('OMNOMNOM_REDIS_HOST') or 'localhost'
    frontend_logger.debug('Redis host: %s' % redis_host)

    cache = redis.Redis(host=redis_host, decode_responses=True)

    token = os.environ.get('OMNOMNOM_AUTH_TOKEN')
    if not token:
        frontend_logger.error('You have to set your auth token as environment variable in OMNOMNOM_AUTH_TOKEN')
        sys.exit()

    admin = os.environ.get('OMNOMNOM_ADMIN')
    if not admin:
        frontend_logger.error('You have to specify an Admin account.')
        sys.exit()
    frontend_logger.debug('Admin ID: %s' % admin)

    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add an error handler to log and report errors
    dispatcher.add_error_handler(error_handler)

    # React to /start, /about and /help messages
    dispatcher.add_handler(CommandHandler('start', help_message), 2)
    dispatcher.add_handler(CommandHandler('about', about), 2)
    dispatcher.add_handler(CommandHandler('help', help_message), 2)

    # Send typing action and log incoming messages
    dispatcher.add_handler(RegexHandler('.*', send_typing_action), 0)
    dispatcher.add_handler(RegexHandler('.*', log_incoming_messages), 1)

    # Handle all messages beginning with a '/'
    dispatcher.add_handler(RegexHandler('/.*', menu), 2)

    # Handle normal text messages that are no reply and answer with a help_message
    dispatcher.add_handler(MessageHandler(Filters.text & (~ Filters.reply), help_message), 2)

    # Handle group member changes
    dispatcher.add_handler(MessageHandler(Filters.group & (~ Filters.reply), group_message_handler), 3)

    send_message_to_admin.delay('*Bot Started*\n\nID: %s\nFirstname: %s\nLastname: %s\nUsername: %s\nName: %s' %
                                (updater.bot.id, updater.bot.first_name, updater.bot.last_name,
                                 updater.bot.username, updater.bot.name))

    frontend_logger.info('Start polling')
    updater.start_polling()
    updater.idle()
예제 #8
0
Now, anyone using "/get notedata", or "#notedata" will be replied to with "This is some data!".

If you want to save an image, gif, or sticker, or any other data, do the following:
`/save notename` while replying to a sticker or whatever data you'd like. Now, the note at "#notename" contains a sticker which will be sent as a reply.

Tip: to retrieve a note without the formatting, use /get <notename> noformat
This will retrieve the note and send it without formatting it; getting you the raw markdown, allowing you to make easy edits.
"""

__mod_name__ = "Notes"

GET_HANDLER = CommandHandler("get", cmd_get, pass_args=True, run_async=True)
HASH_GET_HANDLER = MessageHandler(
    Filters.regex(r"^#[^\s]+") & ~Filters.chat_type.channel,
    hash_get,
    run_async=True,
)

SAVE_HANDLER = CommandHandler("save", save, run_async=True)
DELETE_HANDLER = CommandHandler("clear", clear, pass_args=True, run_async=True)

LIST_HANDLER = DisableAbleCommandHandler(["notes", "saved"],
                                         list_notes,
                                         admin_ok=True,
                                         run_async=True)
CLEARALLNOTES_HANDLER = CommandHandler("rmallnotes",
                                       clear_notes,
                                       filters=Filters.chat_type.groups,
                                       run_async=True)
예제 #9
0
            if update.message.text == command.command:
                command.handler(tg_group_id, update.message.from_user)
                raise DispatcherHandlerStop()

    qq_group_id, _, forward_index = get_forward_index(tg_group_id=int(tg_group_id))
    if forward_index == -1:
        raise DispatcherHandlerStop()

    for command in global_vars.command_list:  # process all forward commands
        if not command.tg_only and not command.qq_only:
            if update.message.text == command.command:
                command.handler(forward_index, tg_group_id, update.message.from_user, qq_group_id, 0)
                raise DispatcherHandlerStop()


global_vars.dp.add_handler(MessageHandler(Filters.text, tg_command), 0)  # priority 0


@global_vars.qq_bot.listener((RcvdGroupMessage, ), 0)  # priority 0
def qq_drive_mode(message):
    qq_group_id = int(message.group)
    text = message.text  # get message text
    text, _ = re.subn('&amp;', '&', text)  # restore characters
    text, _ = re.subn('&#91;', '[', text)
    text, _ = re.subn('&#93;', ']', text)
    text, _ = re.subn('&#44;', ',', text)

    for command in global_vars.command_list:  # process all non-forward commands
        if command.qq_only:
            if text == command.command:
                command.handler(qq_group_id, int(message.qq))
예제 #10
0
def run():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    updater = Updater(token=config.TOKEN)
    utils.setup_updater(updater)
    updater.dispatcher.add_error_handler(error_handler)
    updater.dispatcher.add_handler(
        MessageHandler(Filters.document.file_extension("torrent"), torrent_file_handler)
    )
    updater.dispatcher.add_handler(
        MessageHandler(Filters.regex(r"\Amagnet:\?xt=urn:btih:.*"), magnet_url_handler)
    )
    updater.dispatcher.add_handler(CommandHandler("start", start))
    updater.dispatcher.add_handler(CommandHandler("menu", start))
    updater.dispatcher.add_handler(CommandHandler("add", add))
    updater.dispatcher.add_handler(CommandHandler("memory", memory))
    updater.dispatcher.add_handler(CommandHandler("torrents", get_torrents_command))
    updater.dispatcher.add_handler(CommandHandler("settings", settings_menu_command))
    updater.dispatcher.add_handler(
        CallbackQueryHandler(settings_menu_inline, pattern="settings")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(change_server_inline, pattern="server\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(change_server_menu_inline, pattern="changeservermenu\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(torrent_adding, pattern="addmenu\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(select_file, pattern="fileselect\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(select_for_download, pattern="selectfiles\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(edit_file, pattern="editfile\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(torrent_adding_actions, pattern="torrentadd\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(torrent_files_inline, pattern="torrentsfiles\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(delete_torrent_inline, pattern="deletemenutorrent\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(delete_torrent_action_inline, pattern="deletetorrent\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(get_torrents_inline, pattern="torrentsgoto\\_*")
    )
    updater.dispatcher.add_handler(
        CallbackQueryHandler(torrent_menu_inline, pattern="torrent\\_*")
    )
    updater.bot.set_my_commands(
        [
            ("start", "Open menu with commands"),
            ("menu", "Open menu with commands"),
            ("torrents", "List all torrents"),
            ("memory", "Available memory"),
            ("add", "Add torrent"),
            ("settings", "Bot settings"),
        ]
    )
    user: dict[str, str] = updater.bot.get_me()
    logger.info(f"Started bot {user['first_name']} at https://t.me/{user['username']}")
    updater.idle()
예제 #11
0
my_id = 534116184

# здесь мы задаем глобальную конфигурацию для всех логеров
logging.basicConfig(level=logging.DEBUG,
                    filename='logs/bot.log',
                    format='%(asctime)s, %(levelname)s, %(message)s, %(name)s')

# а тут настраиваем логгер для текущего файла .py
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = RotatingFileHandler('my_logger.log',
                              maxBytes=50000000,
                              backupCount=5)
logger.addHandler(handler)


def say_hi(bot, update):
    # В ответ на любое сообщение, переданное в аргумент update,
    # будет отправлено сообщение 'Привет, я бот'
    bot.message.reply_text('Привет, я ботик, у меня баги')


# Регистрируется обработчик MessageHandler;
# из всех полученных сообщений он будет выбирать только текстовые сообщения
# и передавать их в функцию say_hi()
updater.dispatcher.add_handler(MessageHandler(Filters.text, say_hi))

# Метод start_polling() запускает процесс polling,
# приложение начнёт отправлять регулярные запросы для получения обновлений.
# updater.start_polling(poll_interval=20.0) - Периодичность опроса
updater.start_polling()
__help__ = """
*Admin only:*
 - /gbanstat <on/off/yes/no>: Will disable the effect of global bans on your group, or return your current settings.

Gbans, also known as global bans, are used by the bot owners to ban spammers across all groups. This helps protect \
you and your groups by removing spam flooders as quickly as possible. They can be disabled for you group by calling \
/gbanstat
"""

__mod_name__ = "Global Bans"

GBAN_HANDLER = CommandHandler("gban", gban, pass_args=True,
                              filters=CustomFilters.sudo_filter | CustomFilters.support_filter)
UNGBAN_HANDLER = CommandHandler("ungban", ungban, pass_args=True,
                                filters=CustomFilters.sudo_filter | CustomFilters.support_filter)
GBAN_LIST = CommandHandler("gbanlist", gbanlist,
                           filters=CustomFilters.sudo_filter | CustomFilters.support_filter)

GBAN_STATUS = CommandHandler("gbanstat", gbanstat, pass_args=True, filters=Filters.group)

GBAN_ENFORCER = MessageHandler(Filters.all & Filters.group, enforce_gban)

dispatcher.add_handler(GBAN_HANDLER)
dispatcher.add_handler(UNGBAN_HANDLER)
dispatcher.add_handler(GBAN_LIST)
dispatcher.add_handler(GBAN_STATUS)

if STRICT_GBAN:  # enforce GBANS if this is set
    dispatcher.add_handler(GBAN_ENFORCER, GBAN_ENFORCE_GROUP)
예제 #13
0
        contents = yaml.load(file)

    STORE = contents

    message = ""
    for (key, value) in STORE.items():
        message += f"\n\n{key} Todos:\n"

        task: str
        for idx, task in enumerate([i for i in value if len(i)]):
            message += f"\n{idx}: {task.title()}"
    context.bot.send_message(chat_id=update.effective_chat.id, text=message)


covid_regex = r'(?i)(COVID|pandemic|corona|covid)'
message_handler = MessageHandler(
    Filters.regex(covid_regex) & (~Filters.command), message_callback)
all_messages = MessageHandler(Filters.all & (~Filters.command),
                              all_message_callback)
gemma_handler = MessageHandler(
    Filters.regex(r'(Gemma)') & (~Filters.command), gemma_callback)

dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('help', help))
dispatcher.add_handler(CommandHandler('hype', hype))
dispatcher.add_handler(CommandHandler('love', love))
dispatcher.add_handler(CommandHandler('fact', fact))
dispatcher.add_handler(CommandHandler('wifi', wifi))
dispatcher.add_handler(CommandHandler('meme', meme))
dispatcher.add_handler(CommandHandler('todo', add_todo))
dispatcher.add_handler(CommandHandler('todos', list_todos))
dispatcher.add_handler(CommandHandler('done', done))
예제 #14
0
    response = requests.post(
        'https://api.funtranslations.com/translate/yoda.json',
        headers=headers,
        data=data)
    json_data = json.loads(response.text)
    translated = json_data['contents']['translated']
    msg += translated
    #context.bot.send_message(chat_id=update.effective_chat.id, text=msg)
    update.message.reply_text(msg)


def run(updater):
    PORT = int(os.environ.get("PORT", "8443"))
    HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME")
    updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)
    updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(
        HEROKU_APP_NAME, TOKEN))


def run1(updater):
    updater.start_polling()


if __name__ == '__main__':
    logger.info("Starting bot")
    updater = Updater(token=TOKEN, use_context=True)
    updater.dispatcher.add_handler(CommandHandler("start", start))
    translator_handler = MessageHandler(Filters.text, translator)
    updater.dispatcher.add_handler(translator_handler)
    run(updater)
예제 #15
0
 • `/blsticker`*:* See current blacklisted sticker.
*Only admin:*
 • `/addblsticker <sticker link>`*:* Add the sticker trigger to the black list. Can be added via reply sticker.
 • `/unblsticker <sticker link>`*:* Remove triggers from blacklist. The same newline logic applies here, so you can delete multiple triggers at once.
 • `/rmblsticker <sticker link>`*:* Same as above.
 • `/blstickermode <ban/tban/mute/tmute>`*:* sets up a default action on what to do if users use blacklisted stickers. (`tmute seems broken right now`)
Note:
 • `<sticker link>` can be `https://t.me/addstickers/<sticker>` or just `<sticker>` or reply to the sticker message.
"""

__mod_name__ = "Sticker Blacklist"

BLACKLIST_STICKER_HANDLER = DisableAbleCommandHandler("blsticker",
                                                      blackliststicker,
                                                      pass_args=True,
                                                      admin_ok=True)
ADDBLACKLIST_STICKER_HANDLER = DisableAbleCommandHandler(
    "addblsticker", add_blackliststicker)
UNBLACKLIST_STICKER_HANDLER = CommandHandler(["unblsticker", "rmblsticker"],
                                             unblackliststicker)
BLACKLISTMODE_HANDLER = CommandHandler("blstickermode",
                                       blacklist_mode,
                                       pass_args=True)
BLACKLIST_STICKER_DEL_HANDLER = MessageHandler(Filters.sticker & Filters.group,
                                               del_blackliststicker)

dispatcher.add_handler(BLACKLIST_STICKER_HANDLER)
dispatcher.add_handler(ADDBLACKLIST_STICKER_HANDLER)
dispatcher.add_handler(UNBLACKLIST_STICKER_HANDLER)
dispatcher.add_handler(BLACKLISTMODE_HANDLER)
dispatcher.add_handler(BLACKLIST_STICKER_DEL_HANDLER)
예제 #16
0
import logging
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters

TOKEN = "299340164:AAH4877NeLmLF9XfxNdVVFLhC7sFGKeH69M"

updater = Updater(token=TOKEN)
dispatcher = updater.dispatcher


def start(bot, update):
    bot.sendMessage(chat_id=update.message.chat_id,
                    text="I'm a bot, please talk to me!")


def echo(bot, update):
    bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)


start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

echo_handler = MessageHandler(Filters.text, echo)
dispatcher.add_handler(echo_handler)

updater.start_polling()
예제 #17
0
def __migrate__(old_chat_id, new_chat_id):
    sql.migrate_chat(old_chat_id, new_chat_id)


def __chat_settings__(chat_id, user_id):
    notes = sql.get_all_chat_notes(chat_id)
    return tl(user_id, "There are `{}` notes in this chat.").format(len(notes))


__help__ = "notes_help"

__mod_name__ = "Notes"

GET_HANDLER = CommandHandler("get", cmd_get, pass_args=True)
HASH_GET_HANDLER = MessageHandler(Filters.regex(r"^#[^\s]+"), hash_get)

SAVE_HANDLER = CommandHandler("save", save)
REMOVE_ALL_NOTES_HANDLER = CommandHandler("clearall", remove_all_notes)
DELETE_HANDLER = CommandHandler("clear", clear, pass_args=True)

PMNOTE_HANDLER = CommandHandler("privatenote", private_note, pass_args=True)

LIST_HANDLER = DisableAbleCommandHandler(["notes", "saved"],
                                         list_notes,
                                         admin_ok=True)

dispatcher.add_handler(GET_HANDLER)
dispatcher.add_handler(SAVE_HANDLER)
dispatcher.add_handler(LIST_HANDLER)
dispatcher.add_handler(DELETE_HANDLER)
예제 #18
0
파일: chatbot.py 프로젝트: wrike-3/help_bot
                update.effective_chat.username, query.data)
    query.edit_message_text(text=f"{replies['assessment_thanks']}")


def show_history(update, context):
    logger.info('show history msg %s', update.message.chat.username)
    history = '\n'.join(context.user_data.get('history', 'empty'))
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text=f'User history:\n{history}')


# create chat bot
updater = Updater(token=TOKEN, use_context=True, persistence=my_persistence)
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('info', info))

dispatcher.add_handler(CommandHandler('setmodel', set_model))
for model_name in model_name_dict.keys():
    dispatcher.add_handler(
        CommandHandler(model_name, partial(set_model, model_name=model_name)))
dispatcher.add_handler(CommandHandler('showmodel', show_model))
dispatcher.add_handler(CommandHandler('history', show_history))
dispatcher.add_handler(CommandHandler('addquestion', add_question))
dispatcher.add_handler(CallbackQueryHandler(assessment_button))
dispatcher.add_handler(MessageHandler(Filters.text & (~Filters.command),
                                      reply))

updater.start_polling()
예제 #19
0
Admin only:
 • `/addblacklist <triggers>`*:* Add a trigger to the blacklist. Each line is considered one trigger, so using different lines will allow you to add multiple triggers.
 • `/unblacklist <triggers>`*:* Remove triggers from the blacklist. Same newline logic applies here, so you can remove multiple triggers at once.
 • `/blacklistmode <off/del/warn/ban/kick/mute/tban/tmute>`*:* Action to perform when someone sends blacklisted words.

"""
BLACKLIST_HANDLER = DisableAbleCommandHandler(
    "blacklist", blacklist, pass_args=True, admin_ok=True,
)
ADD_BLACKLIST_HANDLER = CommandHandler("addblacklist", add_blacklist)
UNBLACKLIST_HANDLER = CommandHandler("unblacklist", unblacklist)
BLACKLISTMODE_HANDLER = CommandHandler("blacklistmode", blacklist_mode, pass_args=True)
BLACKLIST_DEL_HANDLER = MessageHandler(
    (Filters.text | Filters.command | Filters.sticker | Filters.photo) & Filters.group,
    del_blacklist,
    allow_edit=True,
)

dispatcher.add_handler(BLACKLIST_HANDLER)
dispatcher.add_handler(ADD_BLACKLIST_HANDLER)
dispatcher.add_handler(UNBLACKLIST_HANDLER)
dispatcher.add_handler(BLACKLISTMODE_HANDLER)
dispatcher.add_handler(BLACKLIST_DEL_HANDLER, group=BLACKLIST_GROUP)

__handlers__ = [
    BLACKLIST_HANDLER,
    ADD_BLACKLIST_HANDLER,
    UNBLACKLIST_HANDLER,
    BLACKLISTMODE_HANDLER,
    (BLACKLIST_DEL_HANDLER, BLACKLIST_GROUP),
예제 #20
0
파일: bot.py 프로젝트: ftlka/tg_chatbot
from telegram.ext import Filters, MessageHandler, Updater
import config


def echo(bot, update):
    update.message.reply_text(update.message.text)


if __name__ == '__main__':
    updater = Updater(token=config.TOKEN,
                      request_kwargs={
                          'proxy_url':
                          config.protocol + config.ip + config.port
                      })
    updater.dispatcher.add_handler(MessageHandler(Filters.text, echo))
    updater.start_polling()
    updater.idle()
예제 #21
0
# Initial bot by Telegram access token
bot = telegram.Bot(token=(config['TELEGRAM']['ACCESS_TOKEN']))


@app.route('/hook', methods=['POST'])
def webhook_handler():
    """Set route /hook with POST method will trigger this method."""
    if request.method == "POST":
        update = telegram.Update.de_json(request.get_json(force=True), bot)

        # Update dispatcher process that handler to process this message
        dispatcher.process_update(update)
    return 'ok'


def reply_handler(bot, update):
    """Reply message."""
    text = update.message.text
    update.message.reply_text(text)


# New a dispatcher for bot
dispatcher = Dispatcher(bot, None)

# Add handler for handling message, there are many kinds of message. For this handler, it particular handle text
# message.
dispatcher.add_handler(MessageHandler(Filters.text, reply_handler))

if __name__ == "__main__":
    # Running server
    app.run(debug=True)
예제 #22
0
                                   forwarder.first_name, forwarder.id),
                               parse_mode=ParseMode.MARKDOWN)

        else:
            # Replied message is a message from a user
            user = message.reply_to_message.from_user
            message.reply_text("{}ايدي هو  `{}`.".format(
                user.first_name, user.id),
                               parse_mode=ParseMode.MARKDOWN)

    else:
        chat = update.effective_chat

        if chat.type == "private":  # Private chat with the bot
            message.reply_text("ايديك هو `{}`.".format(chat.id),
                               parse_mode=ParseMode.MARKDOWN)

        else:  # Group chat where the bot is a member
            message.reply_text("ايدي القناة أو القروب `{}`.".format(chat.id),
                               parse_mode=ParseMode.MARKDOWN)


GET_ID_HANDLER = MessageHandler(
    Filters.command & Filters.regex(r"^/id") &
    (Filters.user(OWNER_ID) | Filters.update.channel_posts),
    get_id,
    run_async=True,
)

dispatcher.add_handler(GET_ID_HANDLER)
예제 #23
0
파일: bot.py 프로젝트: chuikoilya98/hooker
            context.bot.send_message(chat_id=user, text=message)

    else:
        pass


if __name__ == "__main__":

    bot = telegram.Bot(token=tgToken)
    updater = Updater(token=tgToken, use_context=True)
    dispatcher = updater.dispatcher

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            NAME: [MessageHandler(Filters.text, getTime)],
            TIME: [MessageHandler(Filters.text, getGuests)],
            GUESTS: [MessageHandler(Filters.text, getHoldTime)],
            TIMETOHOLD: [MessageHandler(Filters.text, getPhone)],
            PHONE: [MessageHandler(Filters.contact, finish)]
        },
        fallbacks=[CommandHandler('cancel', cancel)])

    mailing_handler = MessageHandler(Filters.text, mailing)

    #test_handler= CommandHandler('test',test)
    #dispatcher.add_handler(test_handler)

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)
예제 #24
0
import logging.config

from telegram.ext import CommandHandler, MessageHandler

import modules.utils as utils
from modules.handlers import commands_handlers_dict, messages_handlers_dict


if __name__ == '__main__':
    logging.config.dictConfig(utils.config['logging'])

    dispatcher = utils.updater.dispatcher
    for handler_name, handler_func in commands_handlers_dict.items():
        dispatcher.add_handler(CommandHandler(handler_name, handler_func, pass_args=True))
    for handler_filter, handler_func in messages_handlers_dict.items():
        dispatcher.add_handler(MessageHandler(handler_filter, handler_func))

    logging.info('Start bot')
    utils.updater.start_polling()
예제 #25
0
__mod_name__ = "Chatbot"

__help__ = f"""
Chatbot utilizes the CoffeeHouse API and allows Saitama to talk and provides a more interactive group chat experience.

*Commands:* 
*Admins only:*
 • `/addchat`*:* Enables Chatbot mode in the chat.
 • `/rmchat`*:* Disables Chatbot mode in the chat.
 
*Dragons or higher only:* 
 • `/listaichats`*:* Lists the chats the chatmode is enabled in.

Reports bugs at {SUPPORT_CHAT}
*Powered by CoffeeHouse* (https://coffeehouse.intellivoid.net/) from @Intellivoid
"""

ADD_CHAT_HANDLER = CommandHandler("addchat", add_chat)
REMOVE_CHAT_HANDLER = CommandHandler("rmchat", remove_chat)
CHATBOT_HANDLER = MessageHandler(
    Filters.text & (~Filters.regex(r"^#[^\s]+") & ~Filters.regex(r"^!")
                    & ~Filters.regex(r"^\/")), chatbot)
LIST_CB_CHATS_HANDLER = CommandHandler(
    "listaichats", list_chatbot_chats, filters=CustomFilters.dev_filter)
# Filters for ignoring #note messages, !commands and sed.

dispatcher.add_handler(ADD_CHAT_HANDLER)
dispatcher.add_handler(REMOVE_CHAT_HANDLER)
dispatcher.add_handler(CHATBOT_HANDLER)
dispatcher.add_handler(LIST_CB_CHATS_HANDLER)
예제 #26
0
            else:
                # LEGACY - all new filters will have has_markdown set to True.
                message.reply_text(filt.reply)
            break


def __stats__():
    return "{} filters, across {} chats.".format(sql.num_filters(),
                                                 sql.num_chats())


def __migrate__(old_chat_id, new_chat_id):
    sql.migrate_chat(old_chat_id, new_chat_id)


def __chat_settings__(bot, update, chat, chatP, user):
    cust_filters = sql.get_chat_triggers(chat.id)
    return "There are `{}` custom filters here.".format(len(cust_filters))


FILTER_HANDLER = CommandHandler("filter", filters)
STOP_HANDLER = CommandHandler("stop", stop_filter)
LIST_HANDLER = CommandHandler("filters", list_handlers)
CUST_FILTER_HANDLER = MessageHandler(CustomFilters.has_text, reply_filter)

dispatcher.add_handler(FILTER_HANDLER)
dispatcher.add_handler(STOP_HANDLER)
dispatcher.add_handler(LIST_HANDLER)
dispatcher.add_handler(CUST_FILTER_HANDLER, HANDLER_GROUP)
예제 #27
0
__help__ = """
We're all busy people who don't have time to monitor our groups 24/7. But how do you \
react if someone in your group is spamming?

Presenting reports; if someone in your group thinks someone needs reporting, they now have \
an easy way to call all admins.

*Admin only:*
 ✗ /reports <on/off>: Change report setting, or view current status.
   • If done in pm, toggles your status.
   • If in chat, toggles that chat's status.

To report a user, simply reply to user's message with @admin or /report. \
This message tags all the chat admins; same as if they had been @'ed.
You MUST reply to a message to report a user; you can't just use @admin to tag admins for no reason!

Note that the report commands do not work when admins use them; or when used to report an admin. Bot assumes that \
admins don't need to report, or be reported!
"""
REPORT_HANDLER = CommandHandler("report", report, filters=Filters.group)
SETTING_HANDLER = CommandHandler("reports", report_setting, pass_args=True)
ADMIN_REPORT_HANDLER = MessageHandler(Filters.regex("(?i)@admin(s)?"), report)
REPORT_BUTTON_HANDLER = CallbackQueryHandler(report_buttons,
                                             pattern=r"report_")

dispatcher.add_handler(REPORT_HANDLER, REPORT_GROUP)
dispatcher.add_handler(ADMIN_REPORT_HANDLER, REPORT_GROUP)
dispatcher.add_handler(SETTING_HANDLER)
dispatcher.add_handler(REPORT_BUTTON_HANDLER)
예제 #28
0
    user.save()
    up.effective_message.reply_text(
        T("Thanks for the email. You're all set-up now."))
    show_help(bot, up)

    return ConversationHandler.END


dispatcher.add_handler(
    ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
            recv_phone_number.__name__: [
                MessageHandler(Filters.contact,
                               recv_phone_number,
                               pass_chat_data=True),
                MessageHandler(Filters.text,
                               recv_phone_number,
                               pass_chat_data=True),
            ],
            recv_email.__name__:
            [MessageHandler(Filters.text, recv_email, pass_chat_data=True)],
        },
        fallbacks=[ABORT, CommandHandler("start", start)],
    ))


@util.login_required
def book(_, up: tg.Update):
    up.effective_message.reply_text(
예제 #29
0
    # Enable logging
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)
    logger = logging.getLogger(__name__)

    # Set up the Updater
    updater = Updater(TOKEN)
    dp = updater.dispatcher
    # Add handlers
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            CHOOSING_HOME_TEAM: [
                MessageHandler(Filters.text, team_home, pass_user_data=True),
            ],
            CHOOSING_AWAY_TEAM: [
                MessageHandler(Filters.text, team_away, pass_user_data=True),
            ],
            FINAL: [
                MessageHandler(Filters.text,
                               final_message,
                               pass_user_data=True),
            ],
        },
        fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)])

    dp.add_handler(conv_handler)
    #dp.add_handler(error)
예제 #30
0

def __help__(update: Update) -> str:
    return get_string("blacklist", "HELP",
                      lang.get_lang(update.effective_chat.id))


BLACKLIST_HANDLER = DisableAbleCommandHandler("blacklist",
                                              blacklist,
                                              filters=Filters.group,
                                              pass_args=True,
                                              run_async=True)
ADD_BLACKLIST_HANDLER = CommandHandler("addblacklist",
                                       add_blacklist,
                                       filters=Filters.group,
                                       run_async=True)
UNBLACKLIST_HANDLER = CommandHandler(["unblacklist", "rmblacklist"],
                                     unblacklist,
                                     filters=Filters.group,
                                     run_async=True)
BLACKLIST_DEL_HANDLER = MessageHandler(
    (Filters.text | Filters.command | Filters.sticker | Filters.photo)
    & Filters.group,
    del_blacklist,
    run_async=True)

dispatcher.add_handler(BLACKLIST_HANDLER)
dispatcher.add_handler(ADD_BLACKLIST_HANDLER)
dispatcher.add_handler(UNBLACKLIST_HANDLER)
dispatcher.add_handler(BLACKLIST_DEL_HANDLER, group=BLACKLIST_GROUP)
예제 #31
0
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=
        "Bienvenid@ a la version demo del primer robot de Matayoshi. Usted está siendo testigo del comienzo como programador del mejor crack de la historia, vaya suerte que tiene..."
    )


from telegram.ext import CommandHandler
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
updater.start_polling()


def echo(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text=update.message.text)


from telegram.ext import MessageHandler, Filters
echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dispatcher.add_handler(echo_handler)


def caps(update, context):
    text_caps = ' '.join(context.args).upper()
    context.bot.send_message(chat_id=update.effective_chat.id, text=text_caps)


caps_handler = CommandHandler('caps', caps)
dispatcher.add_handler(caps_handler)
예제 #32
0
 def test_other_update_types(self, false_update):
     handler = MessageHandler(None, self.callback_basic, edited_updates=True)
     assert not handler.check_update(false_update)
예제 #33
0
Locking urls will auto-delete all messages with urls, locking stickers will restrict all \
non-admin users from sending stickers, etc.
Locking bots will stop non-admins from adding bots to the chat.

Note:
 • Unlocking permission *info* will allow members (non-admins) to change the group information, such as the description or the group name
 • Unlocking permission *pin* will allow members (non-admins) to pinned a message in a group
"""

__mod_name__ = "Locks"

LOCKTYPES_HANDLER = DisableAbleCommandHandler(
    "locktypes", locktypes, run_async=True
)
# , filters=Filters.chat_type.groups)
LOCK_HANDLER = CommandHandler("lock", lock, pass_args=True, run_async=True)
UNLOCK_HANDLER = CommandHandler(
    "unlock", unlock, pass_args=True, run_async=True
)  # , filters=Filters.chat_type.groups)
# , filters=Filters.chat_type.groups)
LOCKED_HANDLER = CommandHandler("locks", list_locks, run_async=True)

dispatcher.add_handler(LOCK_HANDLER)
dispatcher.add_handler(UNLOCK_HANDLER)
dispatcher.add_handler(LOCKTYPES_HANDLER)
dispatcher.add_handler(LOCKED_HANDLER)

dispatcher.add_handler(
    MessageHandler(Filters.all & Filters.chat_type.groups, del_lockables), PERM_GROUP
)
예제 #34
0
*Admin only*:

 × /setflood <int/'no'/'off'>: enables or disables flood control
 × /setfloodmode <ban/kick/mute/tban/tmute> <value>: Action to perform when user have exceeded flood limit. ban/kick/mute/tmute/tban

 Note:
 - Value must be filled for tban and tmute!

 It can be:
 5m = 5 minutes
 6h = 6 hours
 3d = 3 days
 1w = 1 week
 """

__mod_name__ = "Flood🌀"

FLOOD_BAN_HANDLER = MessageHandler(
    Filters.all & ~Filters.status_update & Filters.group, check_flood)
SET_FLOOD_HANDLER = CommandHandler("setflood", set_flood,
                                   pass_args=True)  #, filters=Filters.group)
SET_FLOOD_MODE_HANDLER = CommandHandler(
    "setfloodmode", set_flood_mode, pass_args=True)  #, filters=Filters.group)
FLOOD_HANDLER = CommandHandler("flood", flood)  #, filters=Filters.group)

dispatcher.add_handler(FLOOD_BAN_HANDLER, FLOOD_GROUP)
dispatcher.add_handler(SET_FLOOD_HANDLER)
dispatcher.add_handler(SET_FLOOD_MODE_HANDLER)
dispatcher.add_handler(FLOOD_HANDLER)
예제 #35
0
    chat_id = update.message.chat_id
    first_name = update.message.from_user.first_name
    last_name = update.message.from_user.last_name
    bot.send_message(
        chat_id=chat_id,
        text=
        f"Hello {first_name} {last_name}, use /cat or /dog for random pics or find out more with /catfact or /dogfact"
    )


def text(bot, update):
    chat_id = update.message.chat_id
    first_name = update.message.from_user.first_name
    bot.send_message(chat_id=chat_id, text=f"Please {first_name}, type /start")


load_dotenv()
TOKEN = os.getenv('TOKEN')

updater = Updater(TOKEN)
dp = updater.dispatcher

dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('dog', dog))
dp.add_handler(CommandHandler('cat', cat))
dp.add_handler(CommandHandler('dogfact', dogfact))
dp.add_handler(CommandHandler('catfact', catfact))
dp.add_handler(MessageHandler(Filters.text, text))

updater.start_polling()
updater.idle()