update examples

This commit is contained in:
Jannes Höke 2016-04-16 19:25:08 +02:00
parent f2a92ccf46
commit 360c3077ea
5 changed files with 64 additions and 66 deletions

View file

@ -18,7 +18,8 @@ Reply to last chat from the command line by typing "/reply <text>"
Type 'stop' on the command line to stop the bot.
"""
from telegram.ext import Updater
from telegram.ext import Updater, StringCommandHandler, StringRegexHandler, \
MessageHandler, CommandHandler, RegexHandler, filters
from telegram.ext.dispatcher import run_async
from time import sleep
import logging
@ -34,8 +35,9 @@ logger = logging.getLogger(__name__)
last_chat_id = 0
# Define a few (command) handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
# Define a few (command) handler callback functions. These usually take the
# two arguments bot and update. Error handlers also receive the raised
# TelegramError object in error.
def start(bot, update):
""" Answer in Telegram """
bot.sendMessage(update.message.chat_id, text='Hi!')
@ -59,13 +61,8 @@ def any_message(bot, update):
update.message.text))
def unknown_command(bot, update):
""" Answer in Telegram """
bot.sendMessage(update.message.chat_id, text='Command not recognized!')
@run_async
def message(bot, update, **kwargs):
def message(bot, update):
"""
Example for an asynchronous handler. It's not guaranteed that replies will
be in order when using @run_async. Also, you have to include **kwargs in
@ -95,16 +92,12 @@ def cli_noncommand(bot, update, update_queue):
appending it to the argument list. Be careful with this though.
Here, we put the input string back into the queue, but as a command.
To learn more about those optional handler parameters, read:
http://python-telegram-bot.readthedocs.org/en/latest/telegram.dispatcher.html
To learn more about those optional handler parameters, read the
documentation of the Handler classes.
"""
update_queue.put('/%s' % update)
def unknown_cli_command(bot, update):
logger.warn("Command not found: %s" % update)
def error(bot, update, error):
""" Print error to console """
logger.warn('Update %s caused error %s' % (update, error))
@ -119,42 +112,43 @@ def main():
dp = updater.dispatcher
# This is how we add handlers for Telegram messages
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", help)
dp.addUnknownTelegramCommandHandler(unknown_command)
dp.addHandler(CommandHandler("start", start))
dp.addHandler(CommandHandler("help", help))
# Message handlers only receive updates that don't contain commands
dp.addTelegramMessageHandler(message)
# Regex handlers will receive all updates on which their regex matches
dp.addTelegramRegexHandler('.*', any_message)
dp.addHandler(MessageHandler([filters.TEXT], message))
# Regex handlers will receive all updates on which their regex matches,
# but we have to add it in a separate group, since in one group,
# only one handler will be executed
dp.addHandler(RegexHandler('.*', any_message), group='log')
# String handlers work pretty much the same
dp.addStringCommandHandler('reply', cli_reply)
dp.addUnknownStringCommandHandler(unknown_cli_command)
dp.addStringRegexHandler('[^/].*', cli_noncommand)
# String handlers work pretty much the same. Note that we have to tell
# the handler to pass the args or update_queue parameter
dp.addHandler(StringCommandHandler('reply', cli_reply, pass_args=True))
dp.addHandler(StringRegexHandler('[^/].*', cli_noncommand,
pass_update_queue=True))
# All TelegramErrors are caught for you and delivered to the error
# handler(s). Other types of Errors are not caught.
dp.addErrorHandler(error)
# Start the Bot and store the update Queue, so we can insert updates
update_queue = updater.start_polling(poll_interval=0.1, timeout=10)
update_queue = updater.start_polling(timeout=10)
'''
# Alternatively, run with webhook:
updater.bot.setWebhook(webhook_url='https://example.com/%s' % token,
certificate=open('cert.pem', 'rb'))
update_queue = updater.start_webhook('0.0.0.0',
443,
url_path=token,
cert='cert.pem',
key='key.key')
key='key.key',
webhook_url='https://example.com/%s'
% token)
# Or, if SSL is handled by a reverse proxy, the webhook URL is already set
# and the reverse proxy is configured to deliver directly to port 6000:
update_queue = updater.start_webhook('0.0.0.0',
6000)
update_queue = updater.start_webhook('0.0.0.0', 6000)
'''
# Start CLI-Loop

View file

@ -17,7 +17,7 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram.ext import Updater
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
import logging
# Enable logging
@ -54,11 +54,11 @@ def main():
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", help)
dp.addHandler(CommandHandler("start", start))
dp.addHandler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.addTelegramMessageHandler(echo)
dp.addHandler(MessageHandler([filters.TEXT], echo))
# log all errors
dp.addErrorHandler(error)

View file

@ -16,12 +16,13 @@ Basic inline bot example. Applies different text transformations.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from random import getrandbits
from uuid import uuid4
import re
from telegram import InlineQueryResultArticle, ParseMode
from telegram.ext import Updater
from telegram import InlineQueryResultArticle, ParseMode, \
InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import logging
# Enable logging
@ -54,26 +55,27 @@ def inlinequery(bot, update):
results = list()
results.append(InlineQueryResultArticle(
id=hex(getrandbits(64))[2:],
id=uuid4(),
title="Caps",
message_text=query.upper()))
input_message_content=InputTextMessageContent(query.upper())))
results.append(InlineQueryResultArticle(
id=hex(getrandbits(64))[2:],
id=uuid4(),
title="Bold",
message_text="*%s*" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN))
input_message_content=InputTextMessageContent(
"*%s*" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN)))
results.append(InlineQueryResultArticle(
id=hex(getrandbits(64))[2:],
id=uuid4(),
title="Italic",
message_text="_%s_" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN))
input_message_content=InputTextMessageContent(
"_%s_" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN)))
bot.answerInlineQuery(update.inline_query.id, results=results)
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
@ -86,11 +88,11 @@ def main():
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", help)
dp.addHandler(CommandHandler("start", start))
dp.addHandler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.addTelegramInlineHandler(inlinequery)
dp.addHandler(InlineQueryHandler(inlinequery))
# log all errors
dp.addErrorHandler(error)

View file

@ -5,8 +5,8 @@
# This program is dedicated to the public domain under the CC0 license.
import logging
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup
from telegram.ext import Updater
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - '
'%(message)s',
@ -55,14 +55,16 @@ def set_value(bot, update):
# Save the user id and the answer to context
context[chat_id] = (user_id, update.message.text)
reply_markup = ReplyKeyboardMarkup([[YES, NO]], one_time_keyboard=True)
reply_markup = ReplyKeyboardMarkup(
[[KeyboardButton(YES), KeyboardButton(NO)]],
one_time_keyboard=True)
bot.sendMessage(chat_id, text="Are you sure?",
reply_markup=reply_markup)
# If we are waiting for confirmation and the right user answered
elif chat_state == AWAIT_CONFIRMATION and chat_context[0] == user_id:
state[chat_id] = MENU
context[chat_id] = None
del state[chat_id]
del context[chat_id]
if text == YES:
values[chat_id] = chat_context[1]
bot.sendMessage(chat_id,
@ -77,8 +79,8 @@ def set_value(bot, update):
# Sets the state back to MENU and clears the context
def cancel(bot, update):
chat_id = update.message.chat_id
state[chat_id] = MENU
context[chat_id] = None
del state[chat_id]
del context[chat_id]
def help(bot, update):
@ -89,12 +91,12 @@ def help(bot, update):
updater = Updater("TOKEN")
# The command
updater.dispatcher.addTelegramCommandHandler('set', set_value)
updater.dispatcher.addHandler(CommandHandler('set', set_value))
# The answer and confirmation
updater.dispatcher.addTelegramMessageHandler(set_value)
updater.dispatcher.addTelegramCommandHandler('cancel', cancel)
updater.dispatcher.addTelegramCommandHandler('start', help)
updater.dispatcher.addTelegramCommandHandler('help', help)
updater.dispatcher.addHandler(MessageHandler([filters.TEXT], set_value))
updater.dispatcher.addHandler(CommandHandler('cancel', cancel))
updater.dispatcher.addHandler(CommandHandler('start', help))
updater.dispatcher.addHandler(CommandHandler('help', help))
# Start the Bot
updater.start_polling()

View file

@ -18,7 +18,7 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram.ext import Updater
from telegram.ext import Updater, CommandHandler
import logging
# Enable logging
@ -73,9 +73,9 @@ def main():
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.addTelegramCommandHandler("start", start)
dp.addTelegramCommandHandler("help", start)
dp.addTelegramCommandHandler("set", set)
dp.addHandler(CommandHandler("start", start))
dp.addHandler(CommandHandler("help", start))
dp.addHandler(CommandHandler("set", set))
# log all errors
dp.addErrorHandler(error)