本文整理汇总了Python中telegram.Bot.set_webhook方法的典型用法代码示例。如果您正苦于以下问题:Python Bot.set_webhook方法的具体用法?Python Bot.set_webhook怎么用?Python Bot.set_webhook使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telegram.Bot
的用法示例。
在下文中一共展示了Bot.set_webhook方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_webhooks
# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import set_webhook [as 别名]
def register_webhooks(force=False):
global BOTS_REGISTERED
if BOTS_REGISTERED and not force:
return
BOTS_REGISTERED = {}
for bot_config in settings.TELEGRAM_BOT:
bot = Bot(bot_config['token'])
if 'webhook' in bot_config:
url = bot_config['webhook'] % bot.token
if url[-1] != '/':
url += '/'
else:
webhook = reverse('telegram_webhook', kwargs={'token': bot.token})
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
url = 'https://' + current_site.domain + webhook
bot.set_webhook(url)
bot = Bot(bot_config['token'])
dispatcher = DjangoDispatcher(bot)
register = import_string(bot_config['register'])
register(dispatcher)
BOTS_REGISTERED[bot.token] = dispatcher
logger.info('bot %s registered on url %s', bot.token, url)
示例2: Updater
# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import set_webhook [as 别名]
#.........这里部分代码省略.........
port=80,
url_path='',
cert=None,
key=None,
clean=False,
bootstrap_retries=0,
webhook_url=None,
allowed_updates=None):
"""
Starts a small http server to listen for updates via webhook. If cert
and key are not provided, the webhook will be started directly on
http://listen:port/url_path, so SSL can be handled by another
application. Else, the webhook will be started on
https://listen:port/url_path
Args:
listen (:obj:`str`, optional): IP-Address to listen on. Default ``127.0.0.1``.
port (:obj:`int`, optional): Port the bot should be listening on. Default ``80``.
url_path (:obj:`str`, optional): Path inside url.
cert (:obj:`str`, optional): Path to the SSL certificate file.
key (:obj:`str`, optional): Path to the SSL key file.
clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
before actually starting the webhook. Default is ``False``.
bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
`Updater` will retry on failures on the Telegram server.
* < 0 - retry indefinitely
* 0 - no retries (default)
* > 0 - retry up to X times
webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
NAT, reverse proxy, etc. Default is derived from `listen`, `port` & `url_path`.
allowed_updates (List[:obj:`str`], optional): Passed to
:attr:`telegram.Bot.set_webhook`.
Returns:
:obj:`Queue`: The update queue that can be filled from the main thread.
"""
with self.__lock:
if not self.running:
self.running = True
# Create & start threads
self.job_queue.start()
self._init_thread(self.dispatcher.start, "dispatcher"),
self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
key, bootstrap_retries, clean, webhook_url, allowed_updates)
# Return the update queue so the main thread can insert updates
return self.update_queue
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean,
allowed_updates):
# """
# Thread target of thread 'updater'. Runs in background, pulls
# updates from Telegram and inserts them in the update queue of the
# Dispatcher.
# """
cur_interval = poll_interval
self.logger.debug('Updater thread started')
self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None)
示例3: TelegramBot
# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import set_webhook [as 别名]
class TelegramBot(IntegrationBot):
"""
Telegram integration.
Permabots only requires token to set webhook and obtain some bot info.
Follow telegram instructions to create a bot and obtain its token `<https://core.telegram.org/bots#botfather>`_.
"""
token = models.CharField(_('Token'), max_length=100, db_index=True, unique=True, validators=[validators.validate_token],
help_text=_("Token provided by Telegram API https://core.telegram.org/bots"))
user_api = models.OneToOneField(TelegramUser, verbose_name=_("Telegram Bot User"), related_name='telegram_bot',
on_delete=models.CASCADE, blank=True, null=True,
help_text=_("Telegram API info. Automatically retrieved from Telegram"))
class Meta:
verbose_name = _('Telegram Bot')
verbose_name_plural = _('Telegram Bots')
def __init__(self, *args, **kwargs):
super(TelegramBot, self).__init__(*args, **kwargs)
self._bot = None
if self.token:
try:
self.init_bot()
except InvalidToken:
logger.warning("Incorrect token %s" % self.token)
def __str__(self):
return "%s" % (self.user_api.first_name or self.token if self.user_api else self.token)
def init_bot(self):
self._bot = TelegramBotAPI(self.token)
@property
def hook_id(self):
return str(self.id)
@property
def hook_url(self):
return 'permabots:telegrambot'
@property
def null_url(self):
return None
@property
def identity(self):
return 'telegram'
def set_webhook(self, url):
self._bot.set_webhook(webhook_url=url)
def message_text(self, message):
return message.text
def get_chat_state(self, message):
try:
return TelegramChatState.objects.select_related('state', 'chat', 'user').get(chat=message.chat, user=message.from_user, state__bot=self.bot)
except TelegramChatState.DoesNotExist:
return None
def build_keyboard(self, keyboard):
if keyboard:
keyboard = ast.literal_eval(keyboard)
keyboard = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
else:
keyboard = ReplyKeyboardHide()
return keyboard
def create_chat_state(self, message, target_state, context):
TelegramChatState.objects.create(chat=message.chat,
user=message.from_user,
state=target_state,
ctx=context)
def get_chat_id(self, message):
return message.chat.id
def send_message(self, chat_id, text, keyboard, reply_message=None, user=None):
parse_mode = ParseMode.HTML
disable_web_page_preview = True
reply_to_message_id = None
if reply_message:
reply_to_message_id = reply_message.message_id
texts = text.strip().split('\\n')
msgs = []
for txt in texts:
for chunk in textwrap.wrap(txt, 4096):
msgs.append((chunk, None))
if keyboard:
msgs[-1] = (msgs[-1][0], keyboard)
for msg in msgs:
try:
logger.debug("Message to send:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,keyboard:%s, reply_to_message_id:%s" %
(chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id))
self._bot.send_message(chat_id=chat_id, text=msg[0], parse_mode=parse_mode,
disable_web_page_preview=disable_web_page_preview, reply_markup=msg[1],
reply_to_message_id=reply_to_message_id)
logger.debug("Message sent OK:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,reply_keyboard:%s, reply_to_message_id:%s" %
(chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id))
#.........这里部分代码省略.........