def start_bot():
my_bot = Updater(settings.TELEGRAM_API_KEY)
dp = my_bot.dispatcher
dp.add_handler(CommandHandler("start", reply_to_start_command))
conv_handler = ConversationHandler(
entry_points=[RegexHandler('^(????????? ??????)$', start_anketa, pass_user_data=True)],
states={
"name": [MessageHandler(Filters.text, get_name, pass_user_data=True)],
"attitude": [RegexHandler('^(1|2|3|4|5)$', attitude, pass_user_data=True)],
"understanding": [RegexHandler('^(1|2|3|4|5)$', understanding, pass_user_data=True)],
"comment": [MessageHandler(Filters.text, comment, pass_user_data=True),
CommandHandler('skip', skip_comment, pass_user_data=True)],
},
fallbacks=[MessageHandler(Filters.text, dontknow, pass_user_data=True)]
)
dp.add_handler(conv_handler)
my_bot.start_polling()
my_bot.idle()
python类CommandHandler()的实例源码
def main():
"""
Simple private telegram bot example.
"""
# Set up logging to log to stdout
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start_handler))
# Enable admin commands for this bot
AdminCommands(dispatcher)
updater.start_polling()
updater.idle()
def register_command(self, commands, callback, allow_edited=False):
"""Registers commands handler
Args:
commands(list|tuple): list of commands to register
callback(function): callable object to execute
allow_edited(Optional[bool]): pass edited messages
Raises:
ValueError: if one of commands in ``commands`` was already registered
"""
for command in commands:
self._register_command(command)
@utils.log(logger, print_ret=False)
def process_update(bot, update):
lang = utils.get_lang(self._storage, update.effective_user)
callback(update.effective_message,
update.effective_message.text.split(' ')[1:], lang)
self._dispatcher.add_handler(CommandHandler(commands, process_update,
allow_edited=allow_edited))
def bot_hook():
"""Entry point for the Telegram connection."""
bot = telegram.Bot(botdata['BotToken'])
dispatcher = Dispatcher(bot, None, workers=0)
dispatcher.add_handler(CommandHandler('Abfahrten', abfahrten, pass_args=True))
dispatcher.add_handler(CommandHandler('abfahrten', abfahrten, pass_args=True))
dispatcher.add_handler(CommandHandler('Abfahrt', abfahrten, pass_args=True))
dispatcher.add_handler(CommandHandler('abfahrt', abfahrten, pass_args=True))
dispatcher.add_handler(CommandHandler('A', abfahrten, pass_args=True))
dispatcher.add_handler(CommandHandler('a', abfahrten, pass_args=True))
dispatcher.add_handler(CommandHandler('Hilfe', hilfe))
dispatcher.add_handler(CommandHandler('hilfe', hilfe))
dispatcher.add_handler(CommandHandler('help', hilfe))
dispatcher.add_handler(MessageHandler(Filters.location, nearest_stations))
update = telegram.update.Update.de_json(request.json, bot)
dispatcher.process_update(update)
return 'OK'
def main():
# define the updater
updater = Updater(token=botconfig.bot_token)
# define the dispatcher
dp = updater.dispatcher
# messages
dp.add_handler(MessageHandler(~Filters.command, util.process_message, edited_updates=True))
dp.add_handler(CommandHandler(('start'), commands.help_command))
dp.add_handler(CommandHandler(('stats'), commands.stats_command))
dp.add_handler(CommandHandler(('globalstats'), commands.global_stats_command))
# handle errors
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
def main():
logger.info("Loading handlers for telegram bot")
# Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
dp = DjangoTelegramBot.dispatcher
# To get Dispatcher related to a specific bot
# dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token
# dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("startgroup", startgroup))
dp.add_handler(CommandHandler("me", me))
dp.add_handler(CommandHandler("chat", chat))
dp.add_handler(MessageHandler(Filters.forwarded , forwarded))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
def main():
logger.info("Loading handlers for telegram bot")
# Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
dp = DjangoTelegramBot.dispatcher
# To get Dispatcher related to a specific bot
# dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token
# dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler([Filters.text], echo))
# log all errors
dp.add_error_handler(error)
# log all errors
dp.addErrorHandler(error)
def start_bot():
my_bot = Updater(settings.TELEGRAM_API_KEY)
my_bot.bot._msg_queue = messagequeue.MessageQueue()
my_bot.bot._is_messages_queued_default = True
jobs = my_bot.job_queue
jobs.run_repeating(my_test, interval=5)
dp = my_bot.dispatcher
dp.add_handler(CommandHandler("start", reply_to_start_command))
dp.add_handler(CommandHandler("subscribe", subscribe_command))
dp.add_handler(CommandHandler("alarm", alarm_command, pass_args=True, pass_job_queue=True))
my_bot.start_polling()
my_bot.idle()
def main(token):
# Create the EventHandler and pass it your bot's token.
updater = Updater(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", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses 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()
def __init__(self):
self.base_pub = rospy.Publisher("/base_controller/command", Twist,
queue_size=1)
token = rospy.get_param('/telegram/token', None)
# Create the Updater and pass it your bot's token.
updater = Updater(token)
# Add command and error handlers
updater.dispatcher.add_handler(CommandHandler('start', self.start))
updater.dispatcher.add_handler(CommandHandler('help', self.help))
updater.dispatcher.add_handler(MessageHandler(Filters.text, self.echo))
updater.dispatcher.add_error_handler(self.error)
# Start the Bot
updater.start_polling()
def __init__(self):
self.history = {}
self.updater = Updater(TOKEN)
self.name = str(self).split(' ')[-1][:-1]
self.dp = self.updater.dispatcher
self.dp.add_handler(CommandHandler("start", start))
self.dp.add_handler(CommandHandler("help", help))
self.dp.add_handler(MessageHandler([Filters.text], echo))
self.dp.add_error_handler(error)
self.stories = StoriesHandler()
logger.info('I\'m alive!')
def main():
updater = Updater("321368678:AAG51bIBetB1dGQfi9e-HhZHv3oTa4tPC7s")
# 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", start))
dp.add_handler(CommandHandler("set", set,
pass_args=True,
pass_job_queue=True,
pass_chat_data=True))
dp.add_handler(CommandHandler("unset", unset, pass_chat_data=True))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Block 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()
def test_help(self):
# this tests the help handler. So first insert the handler
def help(bot, update):
update.message.reply_text('Help!')
# Then register the handler with he updater's dispatcher and start polling
self.updater.dispatcher.add_handler(CommandHandler("help", help))
self.updater.start_polling()
# We want to simulate a message. Since we don't care wich user sends it we let the MessageGenerator
# create random ones
update = self.mg.get_message(text="/help")
# We insert the update with the bot so the updater can retrieve it.
self.bot.insertUpdate(update)
# sent_messages is the list with calls to the bot's outbound actions. Since we hope the message we inserted
# only triggered one sendMessage action it's length should be 1.
self.assertEqual(len(self.bot.sent_messages), 1)
sent = self.bot.sent_messages[0]
self.assertEqual(sent['method'], "sendMessage")
self.assertEqual(sent['text'], "Help!")
# Always stop the updater at the end of a testcase so it won't hang.
self.updater.stop()
def test_start(self):
def start(bot, update):
update.message.reply_text('Hi!')
self.updater.dispatcher.add_handler(CommandHandler("start", start))
self.updater.start_polling()
# Here you can see how we would handle having our own user and chat
user = self.ug.get_user(first_name="Test", last_name="The Bot")
chat = self.cg.get_chat(user=user)
update = self.mg.get_message(user=user, chat=chat, text="/start")
self.bot.insertUpdate(update)
self.assertEqual(len(self.bot.sent_messages), 1)
sent = self.bot.sent_messages[0]
self.assertEqual(sent['method'], "sendMessage")
self.assertEqual(sent['text'], "Hi!")
self.updater.stop()
def main():
updater = Updater(TELEGRAM_TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandHandler('help', show_help))
dp.add_handler(ConversationHandler(
entry_points=[CommandHandler('conversar', chat)],
states={
GENRE_SELECTOR: [
RegexHandler(u'^(%s|%s|%s|%s)$' % tuple(GENRE_KEYBOARD[0]), genre)
]
},
fallbacks=[CommandHandler('cancel', cancel_conversation)]
))
dp.add_error_handler(error)
updater.start_polling()
logger.info('Listening...')
updater.idle()
def telegram_command_handle(updater):
"""
????????? ?????? ?? ???? Telegram
:param updater:
:return:
"""
dispatcher = updater.dispatcher
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
help_me_handler = CommandHandler('help', help_me)
dispatcher.add_handler(help_me_handler)
echo_handler = MessageHandler(Filters.text, echo)
dispatcher.add_handler(echo_handler)
def main():
token = open("../token.txt", "r")
log = open("timebot_log.txt", "w")
updater = Updater(token.readline())
token.close()
# 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", start))
dp.add_handler(CommandHandler("set", set, pass_args=True, pass_job_queue=True))
dp.add_handler(CommandHandler("unset", unset, pass_job_queue=True))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Block until the you presses 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()
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(<TOKENNAME>)
# 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", help))
dp.add_handler(CommandHandler("schedule", schedule))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler([Filters.text], echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses 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()
def main():
# Create the EventHandler and pass it your bot's token.
# sara
#updater = Updater("223436029:AAEgihik3KXielXe7lBuP9H7o4M-eUdL_LU")
#testbot
updater = Updater("223436029:AAH9iIhGXP8EAB4qxXx4wJ0-YpYtplYVOkY")
# 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", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler([Filters.text], chatter))
# Start the Bot
updater.start_polling()
# Run the bot until the you presses 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()
def main():
test_handler = MessageHandler(Filters.all, test, edited_updates=True, message_updates=False)
start_handler = CommandHandler("start", start)
help_handler = CommandHandler("help", get_help)
migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats)
# dispatcher.add_handler(test_handler)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(help_handler)
dispatcher.add_handler(migrate_handler)
# dispatcher.add_error_handler(error_callback)
if HEROKU:
port = int(os.environ.get('PORT', 5000))
updater.start_webhook(listen="0.0.0.0",
port=port,
url_path=TOKEN)
updater.bot.set_webhook("https://tgpolbot.herokuapp.com/" + TOKEN)
else:
updater.start_polling()
updater.idle()
def main():
updater = Updater(cfg['botapi_token'])
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("ping", ping))
# on no command
dp.add_handler(MessageHandler(Filters.text & (~ Filters.forwarded), echo)) # Message is text and is not forwarded
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until process receives SIGINT, SIGTERM or SIGABRT
updater.idle()
def __init__(self, token, db_url):
# connect to Telegram with the desired token
self.updater = Updater(token=token)
self.bot = self.updater.bot
# configure the bot behavior
dispatcher = self.updater.dispatcher
dispatcher.add_handler(CommandHandler("start", self.send_welcome))
dispatcher.add_handler(MessageHandler([Filters.text], self.filter_tags))
# create a digester backed by the desired database
try:
self.digester = digester.Digester(db_url)
except Exception as e:
self.stop()
raise e
self.db_url = db_url
# dispatcher methods
self.get_config = self.digester.get_config
self.get_chat = self.bot.getChat
def main():
updater = Updater(AUTHTOKEN, workers=10)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('help', help))
dp.add_handler(CommandHandler('info', info))
dp.add_handler(CommandHandler('support', support, pass_chat_data=True))
dp.add_handler(CommandHandler('getStats', getMessageStats))
dp.add_handler(CommandHandler('chooselang', chooseLanguage, pass_chat_data=True, pass_args=True))
dp.add_handler(MessageHandler(Filters.voice, receiveMessage, pass_chat_data=True))
dp.add_handler(MessageHandler(Filters.all, countme))
dp.add_handler(CallbackQueryHandler(callbackHandler, pass_chat_data=True))
dp.add_error_handler(error)
updater.start_polling()
logger.debug("Setiup complete, Idling.")
updater.idle()
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("321091178:AAG5ve7E5keE3zRHJLsmGgs-r3D6OV0UNzc")
# 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", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(InlineQueryHandler(inlinequery))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Block until the user presses 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()
def main():
updater = Updater(AUTHTOKEN, workers=10)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('help', help))
dp.add_handler(CommandHandler('info', info))
dp.add_handler(CommandHandler('support', support, pass_chat_data=True))
dp.add_handler(CommandHandler('getStats', getMessageStats))
dp.add_handler(CommandHandler('chooselang', chooseLanguage, pass_chat_data=True, pass_args=True))
dp.add_handler(MessageHandler(Filters.voice, receiveMessage, pass_chat_data=True))
dp.add_handler(MessageHandler(Filters.all, countme))
dp.add_handler(CallbackQueryHandler(callbackHandler, pass_chat_data=True))
dp.add_error_handler(error)
updater.start_polling()
logger.debug("Setiup complete, Idling.")
updater.idle()
def main():
updater = Updater(args.auth)
logger.setLevel(logLevel[args.llevel])
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('help', help))
dp.add_handler(CommandHandler('modism', modism))
dp.add_handler(CommandHandler('modismstats', modismStats))
dp.add_handler(MessageHandler(Filters.text, receiveMessage))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
def test_ping(self):
# Then register the handler with he updater's dispatcher and start polling
self.updater.dispatcher.add_handler(CommandHandler("ping", command_ping))
self.updater.start_polling()
# create with random user
update = self.mg.get_message(text="/ping")
# We insert the update with the bot so the updater can retrieve it.
self.bot.insertUpdate(update)
# sent_messages is the list with calls to the bot's outbound actions. Since we hope the message we inserted
# only triggered one sendMessage action it's length should be 1.
self.assertEqual(len(self.bot.sent_messages), 1)
sent = self.bot.sent_messages[0]
self.assertEqual(sent['method'], "sendMessage")
self.assertEqual(sent['text'], "pong - v0.4")
# Always stop the updater at the end of a testcase so it won't hang.
self.updater.stop()
def __register_handlers(self):
"""
Registers the admin commands.
"""
self.__dispatcher.add_handler(CommandHandler("adminhelp",
self.__admin_help))
self.__dispatcher.add_handler(CommandHandler("users", self.__get_users))
self.__dispatcher.add_handler(CommandHandler("adduser",
self.__add_user,
pass_args=True))
self.__dispatcher.add_handler(CommandHandler(
"rmuser", self.__rm_user, pass_args=True))
def set_up_commands(self):
commands = {
'start': self.command_help,
'help': self.command_help,
'list': self.command_list,
'choose': self.command_choose,
}
for name, command in commands.items():
self.dispatcher.add_handler(CommandHandler(name, command))
self.dispatcher.add_handler(CallbackQueryHandler(self.command_accept_choice))
self.dispatcher.add_error_handler(self.command_error)
def main():
modloader.load_modules(updater, data)
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('help', help_command, pass_args=True))
dp.add_handler(CommandHandler('about', about))
dp.add_handler(CommandHandler('modules', module_list))
dp.add_handler(CommandHandler('settings', settings))
dp.add_handler(CallbackQueryHandler(language, pattern=r'^settings:lang:\w+$'))
dp.add_error_handler(lambda bot, update, error: logger.exception('Exception was raised',
exc_info=error))
updater.start_polling(clean=True)
logger.info('Bot started in {0:.3} seconds'.format(time.time() - start_time))
updater.idle()
data.save()