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


Python Updater.start_webhook方法代码示例

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


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

示例1: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main(token, url, path):
    TOKEN = token
    updater = Updater(TOKEN)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('roll', roll))
    dp.add_handler(CommandHandler('taiyi', taiyi))
    dp.add_handler(CommandHandler('choice', choice))
    dp.add_handler(CommandHandler('say', say))
    dp.add_handler(CommandHandler('dice', dice))
    dp.add_handler(CommandHandler('test', test))

    dp.add_handler(CommandHandler('rollstart', rollstart))
    dp.add_handler(CommandHandler('rolljoin', rolljoin))
    dp.add_handler(CommandHandler('rolllists', rolllists))
    dp.add_handler(CommandHandler('rollnow', rollnow))
    dp.add_handler(CommandHandler('rollquit', rollquit))
    dp.add_handler(CommandHandler('rollkick', rollkick))

    dp.add_handler(CommandHandler('currency', curr))
    dp.add_handler(CommandHandler('kuro', kuro))

    dp.add_handler(InlineQueryHandler(inline_battery))
    # dp.add_handler(MessageHandler(Filters.text, logg))

    #updater.start_polling()
    updater.start_webhook(listen="0.0.0.0",port=15000,url_path=path)
    updater.bot.setWebhook("https://{}/{}".format(url, path))
    updater.idle()
开发者ID:ykelvis,项目名称:scripts,代码行数:30,代码来源:taiyiBatteryBot.py

示例2: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater(telegram_token)

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

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", helper))

    # on noncommand i.e message
    dp.add_handler(MessageHandler([Filters.text], chat))

    # inline keyboard handler
    #dp.add_handler(telegram.ext.CallbackQueryHandler(scroll))
    # TODO: update messages with time information

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_webhook(listen='95.163.114.6',
                      port=88,
                      url_path='CroCodeBot',
                      key='/home/user/cert/private.key',
                      cert='/home/user/cert/cert.pem',
                      webhook_url='https://95.163.114.6:88/CroCodeBot')
    updater.idle()
开发者ID:EremeykinS,项目名称:CroCodeBot,代码行数:31,代码来源:bot.py

示例3: MultitranBot

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
class MultitranBot(object):
	"""docstring for MultitranBot"""

	def __init__(self, token, update_mode="polling", server_IP="127.0.0.1", webhook_port=443, certificate_path="/tmp"):
		super(MultitranBot, self).__init__()
		self.token = token
		self.update_mode = update_mode
		self.webhook_port = webhook_port
		self.server_IP = server_IP
		self.certificate_path = certificate_path

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

		self.command_handler = UserCommandHandler(dispatcher)

	def run(self):
		if self.update_mode=="polling":
			self.updater.start_polling()
		elif "webhook" in self.update_mode:
			self.updater.start_webhook(listen='127.0.0.1',
									   port=self.webhook_port, url_path=self.token)

			self.updater.bot.setWebhook(webhook_url='https://{0}:443/{1}'.format(self.server_IP,
																				 self.token,
																				 self.webhook_port),
										certificate=open(self.certificate_path,'rb'),
			)

			self.updater.idle()
开发者ID:Highstaker,项目名称:Multitran-telegram-bot,代码行数:32,代码来源:multitran_bot.py

示例4: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main():
    token = os.getenv('VOCABOT_TOKEN')
    if not token:
        logging.critical('NO TOKEN FOUND!')
        sys.exit()

    updater = Updater(token)

    # Now we know bot name, set the user-agent of vocadb api session
    voca_db.set_name(updater.bot.name)

    dp = updater.dispatcher

    # Add main handlers
    dp = add_update_handlers(dp)

    # Also add our "log everything" error handler
    dp.add_error_handler(error)

    updater_type = os.getenv('VOCABOT_UPDATER_TYPE', 'POLLING')
    if updater_type == 'POLLING':
        # Start fetching updates
        updater.start_polling()
    elif updater_type == 'WEBHOOK':
        # Sample config:
        listen = os.getenv('VOCABOT_LISTEN')
        port = int(os.getenv('VOCABOT_PORT'))
        url_base = os.getenv('VOCABOT_URL_BASE')
        updater.start_webhook(listen=listen, port=int(port), url_path=token)
        updater.bot.set_webhook(url=url_base + token)

    # Loop till we quit
    updater.idle()
开发者ID:bomjacob,项目名称:VocaBot,代码行数:35,代码来源:main.py

示例5: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater(telegram_token)

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

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", helper))

    # on noncommand i.e message
    dp.add_handler(MessageHandler([Filters.text], chat))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_webhook(listen='95.163.114.6', # 95.163.114.6
                      port=80,
                      url_path='MaraphonBot',
                      key='/home/user/cert/private.key',
                      cert='/home/user/cert/cert.pem',
                      webhook_url='https://95.163.114.6:80/MaraphonBot')
    updater.idle()
开发者ID:EremeykinS,项目名称:MaraphonBot,代码行数:27,代码来源:bot.py

示例6: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main():
    updater = Updater(TOKEN)
    dp = updater.dispatcher

    # Message for new users
    if DEBUG:
        dp.add_handler(CommandHandler('start', start))

    dp.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_user))

    # Ignore all messages until it is called
    #updater.start_polling(clean=True)

    # Wait for termination
    updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)
    updater.bot.set_webhook("https://bienvenida-es-bot.herokuapp.com/" + TOKEN)
    updater.idle()
开发者ID:PGomezGonzalo,项目名称:welcome-tg-bot,代码行数:19,代码来源:main.py

示例7: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main():
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                        level=logging.INFO)

    updater = Updater(token=TOKEN, request_kwargs=SOCKS5_ARGS)
    dispatcher = updater.dispatcher
    tasks = updater.job_queue

    command_handlers = [
        CommandHandler('start', start),
        CommandHandler('help', bot_help),
        CommandHandler('settings', settings),
        CommandHandler('check', check),
        CommandHandler('spy', spy),
        CommandHandler('sound', sound_notifications_mute),
        CommandHandler('bot_pay', bot_pay)
    ]

    regexp_command_handlers = [
        RegexHandler(r'Новинки', check),
        RegexHandler(r'Настройка расписания уведомлений', settings),
        RegexHandler(r'Europe/\w+|Asia/\w+', timezone_set),
        RegexHandler(r'\d{1,2}-\d{1,2}', silent_time),
        RegexHandler(r'\bУведомления\s', spy),
        RegexHandler(r'Меню', start),
        RegexHandler(r'Включить расписание|Выключить расписание', notifications_timer_on_off),
        RegexHandler(r'Настроить расписание|Изменить настройки', set_notifications),
        RegexHandler(r'Звук уведомлений', sound_notifications_mute)
    ]

    append_handlers(dispatcher, command_handlers)
    append_handlers(dispatcher, regexp_command_handlers)

    tasks.run_repeating(updater_task, interval=UPDATER_TASK_TIMER, first=0)

    if DEBUG:
        updater.start_polling()
    else:
        updater.start_webhook(listen='127.0.0.1', port=5000, url_path=TOKEN)
        # certificate=open(CERT_PEM, 'rb')
        updater.bot.set_webhook(url=WEB_HOOK_DOMAIN,
                                certificate=None)
    updater.idle()
开发者ID:AlexeyRadchenko,项目名称:LostFilmBot,代码行数:45,代码来源:bot.py

示例8: main

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def main():
    token = "207013186:AAGimWjXwN9PlvHIW_EWfOgbLAQ3SVIESik"

    updater = Updater(token, workers=2)
    dp = updater.dispatcher
    dp.add_handler(InlineQueryHandler(inlinequery))

    # Commands
    dp.add_handler(CommandHandler("fact", send_fact))
    dp.add_handler(CommandHandler("help", send_help))

    dp.add_error_handler(error)

    updater.start_webhook(
        port=int(os.environ.get("DOKKU_PROXY_PORT")),
        url_path=token,
    )

    print('Listening...')
    logging.info('Listening...')

    updater.idle()
开发者ID:Rostgnom,项目名称:jeff-dean-bot,代码行数:24,代码来源:bot.py

示例9: PictureSenderBot

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
class PictureSenderBot(PicBotRoutines):
	"""docstring for MultitranBot"""

	def __init__(self, token, update_mode="polling", server_ip="127.0.0.1", webhook_port=443, certificate_path="/tmp"):

		self.token = token
		self.database_handler = DatabaseHandler()

		super(PictureSenderBot, self).__init__(token, self.database_handler)

		# for webhooks
		self.update_mode = update_mode
		self.webhook_port = webhook_port
		self.server_IP = server_ip
		self.certificate_path = certificate_path

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

		self.command_handler = UserCommandHandler(self.updater.bot, self.dispatcher, self.database_handler, token=token)

	def run(self):
		if self.update_mode == "polling":
			self.updater.bot.setWebhook()  # clear webhook
			self.updater.start_polling()
			self.updater.idle()

		elif "webhook" in self.update_mode:
			self.updater.start_webhook(listen='127.0.0.1',
									   port=self.webhook_port, url_path=self.token)

			self.updater.bot.setWebhook(webhook_url='https://{0}:443/{1}'.format(self.server_IP,
																				 self.token,
																				 self.webhook_port),
										certificate=open(self.certificate_path, 'rb'),
										)

			self.updater.idle()
开发者ID:Highstaker,项目名称:Picture-sender-telegram-bot,代码行数:40,代码来源:Picture_Sender_Bot.py

示例10: run_bot_service

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
def run_bot_service():
    token = os.environ['BOT_TOKEN']
    updater = Updater(token, workers=10)

    updater.dispatcher.add_handler(get_update_handler())
    updater.dispatcher.add_handler(get_forward_handler())
    updater.dispatcher.add_handler(get_help_handler())

    if CERTIFICATE_PATH:
        webhook_path = generate_random_string(length=20)
        webhook_uri = '/' + webhook_path
        set_webhook(updater, webhook_uri)
        update_queue = updater.start_webhook('0.0.0.0', 5000, webhook_path)
    else:
        update_queue = updater.start_polling(poll_interval=0.1, timeout=10)

    running = True
    while running:
        try:
            time.sleep(20000)
        except KeyboardInterrupt:
            running = False
    updater.stop()
开发者ID:pando85,项目名称:troll-bot,代码行数:25,代码来源:run.py

示例11: UpdaterTest

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.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:BoSicle,项目名称:python-telegram-bot,代码行数:70,代码来源:test_updater.py

示例12: int

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

import requests
from telegram import InlineQueryResultArticle, ParseMode, InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler


token = os.environ.get('TOKEN')
appname = os.environ.get('APPNAME')
osu_token = os.environ.get('OSU')
port = int(os.environ.get('PORT', '5000'))

updater = Updater(token)
updater.start_webhook(listen="0.0.0.0", port=port, url_path=token)
updater.bot.setWebhook("https://{}.herokuapp.com/{}".format(appname, token))

mode_list = {0: 'osu!',
             1: 'Taiko',
             2: 'Catch the Beat',
             3: 'osu!mania'}

with open('country.json') as code:
    country_list = json.load(code)

not_found = [
    InlineQueryResultArticle(id=uuid4(),
                             title="Nothing was found",
                             input_message_content=InputTextMessageContent('( ͡° ͜ʖ ͡°)', parse_mode="Markdown"))]
开发者ID:fumycat,项目名称:osu-bot,代码行数:32,代码来源:osu.py

示例13: unsubscribe

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
    def unsubscribe(bot, update):
        auto_msg.unsubscribe(bot, update)

    dispatcher.add_handler(CommandHandler('start', handler.help))
    dispatcher.add_handler(CommandHandler('help', handler.help))

    dispatcher.add_handler(CommandHandler('quibe', handler.quibe))
    dispatcher.add_handler(CommandHandler('kibe', handler.quibe))

    dispatcher.add_handler(CommandHandler('subscribe', subscribe))
    dispatcher.add_handler(CommandHandler('inscrever', subscribe))

    dispatcher.add_handler(CommandHandler('unsubscribe', unsubscribe))
    dispatcher.add_handler(CommandHandler('desinscrever', unsubscribe))

    dispatcher.add_handler(MessageHandler(Filters.text, handler.unknown))

    if config.MAINTAINER_ID:
        dispatcher.add_handler(CommandHandler('sendto', handler.sendto))
        dispatcher.add_error_handler(handler.error)

    job_queue.run_repeating(lambda bot, job: auto_msg.job(bot), interval=50)

    updater.start_webhook(
        listen='0.0.0.0', port=config.PORT, url_path=config.BOT_TOKEN)

    updater.bot.set_webhook(config.WEBHOOK_URL)

    updater.idle()
开发者ID:caiopo,项目名称:quibe-bot,代码行数:31,代码来源:quibe_bot.py

示例14: Bot

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.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()

    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.add_handler(CommandHandler("start", self.command_help))
        self.dispatcher.add_handler(CommandHandler("help", self.command_help))
        self.dispatcher.add_handler(MessageHandler([Filters.text], self.command_help))
        self.dispatcher.add_handler(InlineQueryHandler(self.inlinequery))
        #self.dispatcher.addErrorHandler(self.error_handle)


    def inlinequery(self, bot, update):
        query = update.inline_query.query
        results = list()

        results.append(InlineQueryResultArticle(id="this id is retrieved from EDICT",
                                                title=query,
                                                input_message_content=InputTextMessageContent(
                                                "%s was not found in the dictionary" % query)))

        bot.answerInlineQuery(update.inline_query.id, results=results)

    def command_help(self, bot, update):
        self.send_message(bot, update.message.chat, _("Welcome to the Japanese-English Dictionary Bot.\n"
                                                      "This bot is created for being used inline and it is global. \n"
                                                      "You can call him in any chat with @jdict_bot\n"
                                                      "Examples: \n"
                                                      "\t\t\[email protected]_bot dog\n"
                                                      "\t\t\[email protected]_bot 犬"))

    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,项目名称:jdict-telegram-bot,代码行数:93,代码来源:bot.py

示例15: int

# 需要导入模块: from telegram.ext import Updater [as 别名]
# 或者: from telegram.ext.Updater import start_webhook [as 别名]
assert token_str in os.environ.keys()

TOKEN = os.environ.get(token_str)
PORT = int(os.environ.get('PORT', '5000'))

#################################################


updater = Updater(TOKEN)

dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('hello', hello))
dispatcher.add_handler(CommandHandler('list', write_list))

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

print("finish set up bot.")

updater.start_webhook(listen="0.0.0.0",
                      port=PORT,
                      url_path=str("tgbot/") + TOKEN)
updater.bot.set_webhook("https://yurasic.herokuapp.com/tgbot/" + TOKEN)

# time to try webhooks
# updater.start_polling()

print("before idle")
updater.idle()
print("after idle")
开发者ID:stoyanovd,项目名称:yurasic,代码行数:32,代码来源:goes.py


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