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类Updater()的实例源码
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 main():
token = CONFIG['token']
proxy = CONFIG.get('proxy', None)
if proxy:
updater = Updater(token, request_kwargs={'proxy_url': proxy})
else:
updater = Updater(token)
dispatcher = updater.dispatcher
for handler in HANDLERS:
dispatcher.add_handler(handler)
start_taskqueue_workers()
updater.start_polling(poll_interval=2, bootstrap_retries=5)
updater.idle()
def setup(webhook_url=None):
"""If webhook_url is not passed, run with long-polling."""
logging.basicConfig(level=logging.WARNING)
if webhook_url:
bot = Bot(TOKEN)
update_queue = Queue()
dp = Dispatcher(bot, update_queue)
else:
updater = Updater(TOKEN)
bot = updater.bot
dp = updater.dispatcher
dp.add_handler(MessageHandler([], example_handler)) # Remove this line
# Add your handlers here
if webhook_url:
bot.set_webhook(webhook_url=webhook_url)
thread = Thread(target=dp.start, name='dispatcher')
thread.start()
return update_queue, bot
else:
bot.set_webhook() # Delete webhook
updater.start_polling()
updater.idle()
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(api_key, workers=64)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on noncommand i.e message - return not found
dp.add_handler(MessageHandler(Filters.command, maintenance))
dp.add_handler(MessageHandler(Filters.text, maintenance))
# log all errors
dp.add_error_handler(error)
# Start the Bot
#updater.start_polling()
updater.start_webhook(listen='127.0.0.1', port=int(listen_port), url_path=api_key)
updater.bot.setWebhook('https://{0}/{1}'.format(domain, api_key))
# 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():
# 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 connect(self):
config = ConfigParser.ConfigParser()
if self.chatnetwork == 'telegram':
try:
config.read(self.keyslocation)
self.telegram_access_token = config.get('telegram','access_token')
self.logger.debug("Successfully read access keys")
except Exception,e:
self.logger.error("Could not read access keys: %s"%e)
sys.exit(1)
try:
self.telegram_bot = telegram.Bot(token=self.telegram_access_token)
self.telegram_updater = Updater(token=self.telegram_access_token)
self.telegram_dispatcher = self.telegram_updater.dispatcher
self.telegram_dispatcher.addTelegramMessageHandler(self.respond)
except Exception,e:
self.logger.error("Telegram bot connect failed: %s"%e)
sys.exit(1)
else:
self.logger.error('Chatnetwork name not correct, found %s'%self.chatnetwork)
return -1
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 __init__(self):
token = rospy.get_param('/telegram/token', None)
if token is None:
rospy.logerr("No token found in /telegram/token param server.")
exit(0)
else:
rospy.loginfo("Got telegram bot token from param server.")
# Set CvBridge
self.bridge = CvBridge()
# Create the EventHandler and pass it your bot's token.
updater = Updater(token)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, self.pub_received))
# log all errors
dp.add_error_handler(self.error)
# Start the Bot
updater.start_polling()
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 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 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():
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 main():
updater = Updater(token=config.TELEGRAM_TOKEN)
print(updater.bot.get_me())
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
jarvis = Jarvis(updater)
interval = datetime.timedelta(seconds=EVENT_TRIGGER_INTERVAL_IN_SECONDS)
updater.job_queue.run_repeating(jarvis.events, interval, first=0)
handlers = [
CommandHandler('start', jarvis.hello),
MessageHandler(Filters.all, jarvis.receive)
]
dispatcher = updater.dispatcher
for handler in handlers:
dispatcher.add_handler(handler)
updater.start_polling()
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(config):
updater = Updater(config['token'])
j = updater.job_queue
def newAlert(bot, job):
'''Polls the GitHub API every 2.5 minutes for new notifications.'''
output = notifications(config)
if output:
bot.sendMessage(chat_id=config['chat_id'], text=output, parse_mode='markdown', \
disable_web_page_preview=True)
job_minute = Job(newAlert, 150.0) #Time in seconds
j.put(job_minute, next_t=0.0)
updater.start_polling()
updater.idle()
def dispatch_telegram_msg(self, events):
"""
Dispatch a telegram push message
:param events: List of events that were found
:type events: dict[models.Event]
:return: None
"""
if not any(events):
return print("[-] No events detected, skipping telegram push notification.")
if not self.config.telegram_api_token:
return print("[-] No telegram api token configured, skipping push notification.")
if not self.config.telegram_api_chat_id:
return print("[-] No telegram chat id configured, skipping push notification.")
bot = Updater(token=self.config.telegram_api_token).bot
bot.sendMessage(chat_id=self.config.telegram_api_chat_id, text=self._get_email_body_from_events(events))
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 __init__(self, channel_id: str, updater: Updater, store: ImgurStore, settings: ImgurSettings):
super().__init__(channel_id, updater)
self.store = store
self.settings = settings
self.post_interval = 10 * 60
def __init__(self, updater: Updater):
super().__init__(updater)
self.store = ImgurStore('imgur',
url=REDIS_URL,
clear_age=ImgurSetup.db_clear_age)
self.commands_handlers = [
CommandHandler('get_tags', self.command_get_tags),
CommandHandler('add_tags', self.command_add_tags, pass_args=True),
CommandHandler('remove_tags', self.command_remove_tags, pass_args=True),
CommandHandler('settings', self.command_get_settings),
CommandHandler('setting', self.command_change_setting, pass_args=True),
]
self.settings = ImgurSettings(self.store)
self.pipe = ImgurPipe(self.name, self.updater, self.store, self.settings)
def __init__(self, channel_id: str, updater: Updater, store: IdStore):
super().__init__(channel_id, updater)
self.store = store
def __init__(self, channel_id: str, updater: Updater, store: RedditStore):
super().__init__(channel_id, updater)
self.store = store
self.limits = []
self.post_interval = 60