当前位置: 首页>>代码示例>>Python>>正文


Python Updater.start_webhook方法代码示例

本文整理汇总了Python中telegram.Updater.start_webhook方法的典型用法代码示例。如果您正苦于以下问题:Python Updater.start_webhook方法的具体用法?Python Updater.start_webhook怎么用?Python Updater.start_webhook使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telegram.Updater的用法示例。


在下文中一共展示了Updater.start_webhook方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]
def main():
    setup_logging()

    updater = Updater(TOKEN, workers=int(os.environ.get('PTB_WORKERS', 2)))

    dp = updater.dispatcher

    dp.addTelegramCommandHandler('start', start)
    addTelegramCommandHandler(dp, 'help', help, 'display help message')
    mensa_help = '\[<date>] get what offerings are waiting for you at the specified date ' \
                 'formatted like \'YYYY-MM-DD\'.'
    addTelegramCommandHandler(dp, 'mensa', mensa_plan_all, mensa_help)
        # alias for autocorrected command
    dp.addTelegramCommandHandler('Mensa', mensa_plan_all)
    addTelegramCommandHandler(dp, 'm', m_plan_keyboard, 'show quick-access menu')

    # shortcuts to direct offers
    for cmd, f, h in SHORTCUTS:
        addTelegramCommandHandler(dp, cmd, f, h)
        dp.addTelegramCommandHandler(cmd.capitalize(), f)

    dp.addTelegramCommandHandler('week', week_plan)

    dp.addErrorHandler(error)
    dp.addUnknownTelegramCommandHandler(unknown)

    if USE_POLLING:
        logging.info('Bot running with polling enabled.')
        update_queue = updater.start_polling(poll_interval=1, timeout=5)
        updater.idle()
    else:
        logging.info('Bot running with webhook.')
        # You can also set the webhook yourself (via cURL) or delete it sending an empty url.
        # Note that for self-signed certificates, you also have to send the .pem certificate file
        # to the Telegram API.
        updater.bot.setWebhook(webhook_url=os.environ.get('PTB_WEBHOOK_URL'))
        update_queue = updater.start_webhook(os.environ.get('PTB_WEBHOOK_LISTEN_IP'),
                                             os.environ.get('PTB_WEBHOOK_LISTEN_PORT'))
开发者ID:me-benni,项目名称:mensa_ukon,代码行数:40,代码来源:bot.py

示例2: UpdaterTest

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]

#.........这里部分代码省略.........

    def test_runAsync(self):
        print('Testing @run_async')
        bot = MockBot('Test5', messages=2)
        self.updater.bot = bot
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(
            self.asyncHandlerTest)
        self.updater.start_polling(0.01)
        sleep(1.2)
        self.assertEqual(self.received_message, 'Test5')
        self.assertEqual(self.message_count, 2)

    def test_additionalArgs(self):
        print('Testing additional arguments for handlers')
        self.updater.bot = MockBot('', messages=0)
        self.updater.dispatcher.addStringCommandHandler(
            'test5', self.additionalArgsTest)

        queue = self.updater.start_polling(0.01)
        queue.put('/test5 resend')
        sleep(.1)
        self.assertEqual(self.received_message, '/test5 noresend')
        self.assertEqual(self.message_count, 2)

    def test_webhook(self):
        print('Testing Webhook')
        bot = MockBot('', messages=0)
        self.updater.bot = bot
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(
            self.telegramHandlerTest)

        # Select random port for travis
        port = randrange(1024, 49152)
        self.updater.start_webhook('127.0.0.1', port,
                                   './tests/test_updater.py',
                                   './tests/test_updater.py',
                                   listen='127.0.0.1')
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester"), datetime.now(),
                          GroupChat(1, "Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        try:
            payload = bytes(update.to_json(), encoding='utf-8')
        except TypeError:
            payload = bytes(update.to_json())

        header = {
            'content-type': 'application/json',
            'content-length': str(len(payload))
        }

        r = Request('http://127.0.0.1:%d/TOKEN' % port,
                    data=payload,
                    headers=header)

        urlopen(r)

        sleep(1)
        self.assertEqual(self.received_message, 'Webhook Test')

        print("Test other webhook server functionalites...")
        request = Request('http://localhost:%d/webookhandler.py' % port)
        response = urlopen(request)
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        request.get_method = lambda: 'HEAD'

        response = urlopen(request)
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        # Test multiple shutdown() calls
        self.updater.httpd.shutdown()
        self.updater.httpd.shutdown()
        self.assertTrue(True)

    def signalsender(self):
        sleep(0.5)
        os.kill(os.getpid(), signal.SIGTERM)

    def test_idle(self):
        print('Testing idle')
        self.updater.bot = MockBot('Test6', messages=0)
        self.updater.start_polling(poll_interval=0.01)
        Thread(target=self.signalsender).start()
        self.updater.idle()
        # If we get this far, idle() ran through
        sleep(1)
        self.updater.running = False
开发者ID:gvaldez81,项目名称:python-telegram-bot,代码行数:104,代码来源:test_updater.py

示例3: UpdaterTest

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]

#.........这里部分代码省略.........
        self.assertEqual(self.received_message, '/test_context')
        self.assertEqual(self.message_count, 1)
        self.assertEqual(self.context, context)

    def test_regexGroupHandler(self):
        self._setup_updater('', messages=0)
        d = self.updater.dispatcher
        d.addStringRegexHandler('^(This).*?(?P<testgroup>regex group).*',
                                self.regexGroupHandlerTest)
        queue = self.updater.start_polling(0.01)
        queue.put('This is a test message for regex group matching.')
        sleep(.1)
        self.assertEqual(self.received_message, (('This', 'regex group'),
                                                 {'testgroup': 'regex group'}))

    def test_runAsyncWithAdditionalArgs(self):
        self._setup_updater('Test6', messages=2)
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(
            self.asyncAdditionalHandlerTest)
        self.updater.start_polling(0.01)
        sleep(1.2)
        self.assertEqual(self.received_message, 'Test6')
        self.assertEqual(self.message_count, 2)

    def test_webhook(self):
        self._setup_updater('', messages=0)
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(
            self.telegramHandlerTest)

        ip = '127.0.0.1'
        port = randrange(1024, 49152)  # Select random port for travis
        self.updater.start_webhook(ip, port,
                                   url_path='TOKEN',
                                   cert='./tests/test_updater.py',
                                   key='./tests/test_updater.py')
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester"), datetime.now(),
                          Chat(1, "group", title="Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN')

        sleep(1)
        self.assertEqual(self.received_message, 'Webhook Test')

        print("Test other webhook server functionalities...")
        response = self._send_webhook_msg(ip, port, None, 'webookhandler.py')
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        response = self._send_webhook_msg(ip, port, None, 'webookhandler.py',
                                          get_method=lambda: 'HEAD')

        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        # Test multiple shutdown() calls
开发者ID:cclauss,项目名称:python-telegram-bot,代码行数:70,代码来源:test_updater.py

示例4: Bot

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]
class Bot(object):
    translations = {}
    bot = None

    def __init__(self):
        self.playing_state = dict()

        self.updater = Updater(token=dungeon.get_bot_conf("TOKEN"))
        self.dispatcher = self.updater.dispatcher
        self.add_handlers()

        try:
            self.tzinfo = timezone(dungeon.get_bot_conf("TIMEZONE"))
        except:
            self.tzinfo = pytz.utc

        # i18n BLOCK (see dungeon world commit 66 / haibot commits)

    def start_polling_loop(self):
        self.disable_webhook()
        self.update_queue = self.updater.start_polling()
        self.updater.idle()
        self.cleaning()

    def start_webhook_server(self):
        self.set_webhook()
        self.update_queue = self.updater.start_webhook(dungeon.get_env_conf("IP","127.0.0.1"),
                                                       int(dungeon.get_env_conf("PORT","8080")),
                                                       dungeon.get_bot_conf("TOKEN"))
        self.updater.idle()
        self.cleaning()

    def cleaning(self):
        dungeon.logger.info("Finished program.")

    def set_webhook(self):
        s = self.updater.bot.setWebhook(dungeon.get_bot_conf("WEBHOOK_URL") + "/" + dungeon.get_bot_conf("TOKEN"))
        if s:
            dungeon.logger.info("webhook setup worked")
        else:
            dungeon.logger.warning("webhook setup failed")
        return s

    def disable_webhook(self):
        s = self.updater.bot.setWebhook("")
        if s:
            dungeon.logger.info("webhook was disabled")
        else:
            dungeon.logger.warning("webhook couldn't be disabled")
        return s

    def add_handlers(self):
        self.dispatcher.addTelegramCommandHandler("start", self.command_start)
        self.dispatcher.addTelegramCommandHandler("help", self.command_help)
        self.dispatcher.addTelegramCommandHandler("exit", self.command_exit)
        self.dispatcher.addTelegramCommandHandler("pj", self.command_pj)
        self.dispatcher.addTelegramCommandHandler("master", self.command_master)
        self.dispatcher.addTelegramCommandHandler("play", self.command_play)

    def get_chat_info(self, update):
        self.last_chat = update.message.chat
        chad_id = update.message.chat.id

        sender = update.message.from_user
        text = update.message.text
        chat_data = db.chats.find_one({"_id" : chad_id})
        if not chat_data:
            chat_data = {"_id" : chad_id, "state" : const.STOPPED, "context": None}

        return chat_data, sender, text

    def command_start(self, bot, update):
        chat, sender, text = self.get_chat_info(update)
        if chat["state"] == const.STOPPED:
            chat["state"] = const.STOPPED
            self.send_message(messages.welcome)
            self.send_message(messages.help[chat["state"]])
        else:
            self.send_message(messages.already_started[chat["state"]])

    def command_help(self, bot, update):
        chat, sender, text = self.get_chat_info(update)
        self.send_message(messages.help[chat["state"]])

    def command_exit(self, bot, update):
        chat, sender, text = self.get_chat_info(update)
        if chat["state"] != const.STOPPED:
            self.send_message(messages.exit[chat["state"]])
            chat["state"] = const.STOPPED
            db.chats.replace_one({"_id":chat["_id"]}, chat, upsert=True )
            chat["context"] = None
        else:
            self.send_message(messages.no_exit)

    def command_pj(self, bot, update):
        chat, sender, text = self.get_chat_info(update)
        if chat["state"] == const.STOPPED:
            chat["state"] = const.NEWPJ
            db.chats.replace_one({"_id":chat["_id"]}, chat, upsert=True )
            self.send_message("guay")
#.........这里部分代码省略.........
开发者ID:haitike,项目名称:dungeon_world_bot,代码行数:103,代码来源:bot.py

示例5: UpdaterTest

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]

#.........这里部分代码省略.........
        sleep(0.5)
        self.assertEqual(self.received_message, "/test_context")
        self.assertEqual(self.message_count, 1)
        self.assertEqual(self.context, context)

    def test_regexGroupHandler(self):
        print("Testing optional groups and groupdict parameters")
        self._setup_updater("", messages=0)
        d = self.updater.dispatcher
        d.addStringRegexHandler("^(This).*?(?P<testgroup>regex group).*", self.regexGroupHandlerTest)
        queue = self.updater.start_polling(0.01)
        queue.put("This is a test message for regex group matching.")
        sleep(0.1)
        self.assertEqual(self.received_message, (("This", "regex group"), {"testgroup": "regex group"}))

    def test_runAsyncWithAdditionalArgs(self):
        print("Testing @run_async with additional parameters")
        self._setup_updater("Test6", messages=2)
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(self.asyncAdditionalHandlerTest)
        self.updater.start_polling(0.01)
        sleep(1.2)
        self.assertEqual(self.received_message, "Test6")
        self.assertEqual(self.message_count, 2)

    def test_webhook(self):
        print("Testing Webhook")
        self._setup_updater("", messages=0)
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(self.telegramHandlerTest)

        # Select random port for travis
        port = randrange(1024, 49152)
        self.updater.start_webhook(
            "127.0.0.1", port, url_path="TOKEN", cert="./tests/test_updater.py", key="./tests/test_updater.py"
        )
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester"), datetime.now(), Chat(1, "group", title="Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        try:
            payload = bytes(update.to_json(), encoding="utf-8")
        except TypeError:
            payload = bytes(update.to_json())

        header = {"content-type": "application/json", "content-length": str(len(payload))}

        r = Request("http://127.0.0.1:%d/TOKEN" % port, data=payload, headers=header)

        urlopen(r)

        sleep(1)
        self.assertEqual(self.received_message, "Webhook Test")

        print("Test other webhook server functionalities...")
        request = Request("http://localhost:%d/webookhandler.py" % port)
        response = urlopen(request)
        self.assertEqual(b"", response.read())
        self.assertEqual(200, response.code)
开发者ID:timotien,项目名称:python-telegram-bot,代码行数:70,代码来源:test_updater.py

示例6: Updater

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]
import os

from datetime import datetime

from bot_token import Token
from calendar_utils import greg2flawless as g2f, flawless_months

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


def now_handler(bot, update):
    fl_today = g2f(datetime.now().date())
    text = "It's the %dth day of %s(%d) %d." % (fl_today[2], flawless_months[fl_today[1]], fl_today[1], fl_today[0])
    bot.sendMessage(chat_id=update.message.chat_id, text=text)


def help_handler(bot, update):
    text = "This bot converts a gregorian date into a flawless date(a particular calendar based on regular months and years)"
    bot.sendMessage(chat_id=update.message.chat_id, text=text)


if __name__ == "__main__":
    dispatcher.addTelegramCommandHandler("now", now_handler)
    dispatcher.addTelegramCommandHandler("help", help_handler)

    # Get the port to bind to
    port = int(os.environ.get("PORT", 5000))
    # Start the updater listening on all public IPs
    updater.start_webhook("0.0.0.0", port)
开发者ID:Ball-Man,项目名称:flawless-calendar,代码行数:32,代码来源:bot.py

示例7: Bot

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]
class Bot(object):
    translations = {}
    bot = None

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read( CONFIGFILE_PATH )

        self.updater = Updater(token=self.get_bot_conf("TOKEN"))
        self.dispatcher = self.updater.dispatcher
        self.add_handlers()

        try:
            self.tzinfo = timezone(self.get_bot_conf("TIMEZONE"))
        except:
            self.tzinfo = pytz.utc

    def get_bot_conf(self, value):
        return self.config["bot"][value]

    def get_env_conf(self, value, default_value=None):
        if default_value:
            return os.environ.get(self.config["env"][value], default_value)
        else:
            return os.environ.get(self.config["env"][value])

    def start_polling_loop(self):
        self.disable_webhook()
        self.update_queue = self.updater.start_polling()
        self.updater.idle()
        self.cleaning()

    def start_webhook_server(self):
        self.set_webhook()
        self.update_queue = self.updater.start_webhook(self.get_env_conf("IP","127.0.0.1"),
                                                       int(self.get_env_conf("PORT","8080")),
                                                       self.get_bot_conf("TOKEN"))
        self.updater.idle()
        self.cleaning()

    def cleaning(self):
        logger.info("Finished program.")

    def set_webhook(self):
        s = self.updater.bot.setWebhook(self.get_bot_conf("WEBHOOK_URL") + "/" + self.get_bot_conf("TOKEN"))
        if s:
            logger.info("webhook setup worked")
        else:
            logger.warning("webhook setup failed")
        return s

    def disable_webhook(self):
        s = self.updater.bot.setWebhook("")
        if s:
            logger.info("webhook was disabled")
        else:
            logger.warning("webhook couldn't be disabled")
        return s

    def add_handlers(self):
        self.dispatcher.addTelegramCommandHandler("start", self.command_start)
        self.dispatcher.addTelegramCommandHandler("help", self.command_help)
        self.dispatcher.addTelegramCommandHandler("time", self.command_time)
        self.dispatcher.addTelegramMessageHandler(self.command_echo)
        #self.dispatcher.addUnknownTelegramCommandHandler(self.command_unknown)
        #self.dispatcher.addErrorHandler(self.error_handle)

    def command_start(self, bot, update):
        self.send_message(bot, update.message.chat, _("Welcome to Dungeon World Bot."))

    def command_help(self, bot, update):
        self.send_message(bot, update.message.chat, _(
            """Available Commands:
            /start - Iniciciate or Restart the bot
            /help - Show the command list.
            /time - Bot local time check"""))

    def command_time(self, bot , update):
        utc_date = datetime.utcnow()
        local_date = pytz.utc.localize(utc_date).astimezone(self.tzinfo)
        formated_string = local_date.strftime("%d/%m/%y %H:%M")
        self.send_message(bot, update.message.chat, formated_string)

    def command_echo(self, bot , update):
        self.send_message(bot, update.message.chat, update.message.text)

    def send_message(self, bot, chat, text):
        try:
            bot.sendMessage(chat_id=chat.id, text=text)
            return True
        except TelegramError as e:
            logger.warning("Message sending error to %s [%d] [%s] (TelegramError: %s)" % (chat.name, chat.id, chat.type, e))
            return False
        except:
            logger.warning("Message sending error to %s [%d] [%s]" % (chat.name, chat.id, chat.type))
            return False
开发者ID:haitike,项目名称:webhook_telegram_bot,代码行数:98,代码来源:bot.py

示例8: HaiBot

# 需要导入模块: from telegram import Updater [as 别名]
# 或者: from telegram.Updater import start_webhook [as 别名]
class HaiBot(object):
    translations = {}
    bot = None

    def __init__(self):
        self.terraria = Terraria()
        self.play_status = None
        self.play_user = None

        #LANGUAGE STUFF
        self.language_list = os.listdir(haibot.config.get("haibot","LOCALE_DIR"))
        for l in self.language_list:
            self.translations[l] = gettext.translation("telegrambot", haibot.config.get("haibot","LOCALE_DIR"), languages=[l], fallback=True)
        try:
            if haibot.config.get("haibot","LANGUAGE") in self.language_list:
                translation_install(self.translations[haibot.config.get("haibot","LANGUAGE")])
            else:
                translation_install(self.translations[DEFAULT_LANGUAGE])
        except:
            translation_install(self.translations[DEFAULT_LANGUAGE])

        # bot INICIALIZATION
        self.updater = Updater(token=haibot.config.get("haibot","TOKEN"))
        self.play_job_queue = self.updater.job_queue
        self.dispatcher = self.updater.dispatcher
        self.add_handlers()

        # Timezone Stuff
        try:
            self.tzinfo = pytz.timezone(haibot.config.get("haibot","TIMEZONE"))
        except:
            self.tzinfo = pytz.utc

    def start_polling_loop(self):
        self.disable_webhook()
        self.update_queue = self.updater.start_polling()
        self.updater.idle()
        self.cleaning()

    def start_webhook_server(self):
        # url/token/server_on |  url/token/server_off | url/token/server_on?hostname |  url/token/server_off?hostname
        from telegram.utils.webhookhandler import WebhookHandler
        from .terraria_server_urls import do_GET
        WebhookHandler.do_GET = do_GET

        self.set_webhook()
        self.update_queue = self.updater.start_webhook(haibot.config.get("haibot","IP"),
                                                       haibot.config.getint("haibot","PORT"),
                                                       haibot.config.get("haibot","TOKEN"))
        self.updater.idle()
        self.cleaning()

    def cleaning(self):
        with open(haibot.CONFIGFILE_PATH, "w") as configfile:
            haibot.config.write(configfile)
            haibot.logger.info("Saving config file...")
        haibot.logger.info("Finished program.")

    def set_webhook(self):
        s = self.updater.bot.setWebhook(haibot.config.get("haibot","WEBHOOK_URL") + "/" + haibot.config.get("haibot","TOKEN"))
        if s:
            haibot.logger.info("webhook setup worked")
        else:
            haibot.logger.warning("webhook setup failed")
        return s

    def disable_webhook(self):
        s = self.updater.bot.setWebhook("")
        if s:
            haibot.logger.info("webhook was disabled")
        else:
            haibot.logger.warning("webhook couldn't be disabled")
        return s

    def add_handlers(self):
        self.dispatcher.addTelegramCommandHandler("start", self.command_start)
        self.dispatcher.addTelegramCommandHandler("help", self.command_help)
        self.dispatcher.addTelegramCommandHandler("terraria", self.command_terraria)
        self.dispatcher.addTelegramCommandHandler("list", self.command_list)
        self.dispatcher.addTelegramCommandHandler("quote", self.command_quote)
        self.dispatcher.addTelegramCommandHandler("search", self.command_search)
        self.dispatcher.addTelegramCommandHandler("autonot", self.command_autonot)
        self.dispatcher.addTelegramCommandHandler("play", self.command_play)
        self.dispatcher.addTelegramCommandHandler("settings",self.command_settings)
        self.dispatcher.addTelegramCommandHandler("profile",self.command_profile)
        self.dispatcher.addUnknownTelegramCommandHandler(self.command_unknown)
        #self.dispatcher.addErrorHandler(self.error_handle)
        self.dispatcher.addStringCommandHandler("terraria_on", self.stringcommand_terraria_on)
        self.dispatcher.addStringCommandHandler("terraria_off", self.stringcommand_terraria_off)
        self.dispatcher.addStringCommandHandler("notify", self.stringcommand_notify)

    @save_user
    def command_start(self, bot, update, args):
        self.send_message(bot, update.message.chat_id, _("Bot was initiated. Use /help for commands."))

    @save_user
    def command_help(self, bot, update, args):
        self.send_message(bot, update.message.chat_id, _(
            """Available Commands:
            /start - Iniciciate or Restart the bot
#.........这里部分代码省略.........
开发者ID:haitike,项目名称:haibot,代码行数:103,代码来源:haibot.py


注:本文中的telegram.Updater.start_webhook方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。