Python telegram.ext 模块,Updater() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用telegram.ext.Updater()

项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
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()
项目:ownbot    作者:michaelimfeld    | 项目源码 | 文件源码
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()
项目:mobot    作者:JokerQyou    | 项目源码 | 文件源码
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()
项目:python-telegram-bot-openshift    作者:lufte    | 项目源码 | 文件源码
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()
项目:RaiWalletBot    作者:SergiySW    | 项目源码 | 文件源码
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()
项目:ImgurPlus    作者:DcSoK    | 项目源码 | 文件源码
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()
项目:jatayu    作者:debayan    | 项目源码 | 文件源码
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
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
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()
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
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()
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
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()
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
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()
项目:ConvAI-baseline    作者:deepmipt    | 项目源码 | 文件源码
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!')
项目:pyttrex    作者:icoprimers    | 项目源码 | 文件源码
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()
项目:heydjbot    作者:mongonauta    | 项目源码 | 文件源码
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()
项目:TBot8-1    作者:Danzilla-cool    | 项目源码 | 文件源码
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()
项目:TBot8-1    作者:Danzilla-cool    | 项目源码 | 文件源码
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()
项目:Sarabot    作者:AlexR1712    | 项目源码 | 文件源码
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()
项目:GrammarNaziBot    作者:SlavMetal    | 项目源码 | 文件源码
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()
项目:totally-not-jarvis    作者:lorey    | 项目源码 | 文件源码
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()
项目:HashDigestBot    作者:wagnerluis1982    | 项目源码 | 文件源码
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
项目:Triton    作者:ArionMiles    | 项目源码 | 文件源码
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()
项目:Remote-Integrity-Tool    作者:DearBytes    | 项目源码 | 文件源码
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))
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
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()
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
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()
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
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()
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
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()
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
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
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
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)
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, channel_id: str, updater: Updater, store: IdStore):
        super().__init__(channel_id, updater)
        self.store = store
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, channel_id: str, updater: Updater, store: RedditStore):
        super().__init__(channel_id, updater)
        self.store = store
        self.limits = []
        self.post_interval = 60
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, updater: Updater):
        super().__init__(updater)
        self.commands_handlers = [
            CommandHandler('add', self.command_add, pass_args=True),
            CommandHandler('remove', self.command_remove, pass_args=True),
            CommandHandler('show', self.command_list),
        ]
        self.store = RedditStore('reddit',
                                 url=REDIS_URL,
                                 clear_age=RedditSetup.db_clear_age)
        self.pipe = RedditPipe(self.name, self.updater, self.store)
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, channel_id: str, updater: Updater):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.channel_id = channel_id
        self.updater = updater
        self.scheduler = Scheduler(self.updater.job_queue)
        self.post_interval = 60
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, updater: Updater):
        """
        - name: name of channel in telegram. **Must** starts with "@".
        - label: identifier for channel. **Must** be unique.
        - pipe_classes:
        - commands_handlers: list of command handlers which would be attached when we need them and detached when we don't.

        :param updater: bot updater.
        """
        self.label = self.__class__.__name__
        self.updater = updater
        self.dispatcher = updater.dispatcher
        self.commands_handlers = []
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, channel_id: str, updater: Updater):
        self.channel_id = channel_id
        self.bot = updater.bot
        self.logger = logging.getLogger(self.__class__.__name__)
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, token: str):
        self.token = token
        self.logger = logging.getLogger(self.__class__.__name__)
        self.updater = Updater(token)
        self.dispatcher = self.updater.dispatcher
        self.chosen_channel = None
        self.admins = None
项目:eddie    作者:greenkey    | 项目源码 | 文件源码
def __init__(self, token):
        self._telegram = Updater(token)
        self._token = token
        self._bot = None
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def set_up(self, updater: Updater):
        self.updater = updater
        self.dispatcher = updater.dispatcher
        active_user_filter = ActiveUsersFilter(self.active_users)
        for handler in self.commands_handlers:
            handler.filters = active_user_filter
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def set_up(self, channel_id: str, updater: Updater, **kwargs):
        self.channel_id = channel_id
        self.updater = updater
        self.scheduler = Scheduler(self.updater.job_queue)
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, token: str, admins=None):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.token = token
        self.updater = Updater(token)
        self.dispatcher = self.updater.dispatcher

        self.channels = {}
        self.chosen_channels = {}
        self.admins = admins
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, channel_id: str, updater: Updater):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.channel_id = channel_id
        self.bot = updater.bot
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def set_up(self, channel_id: str, updater: Updater, **kwargs):
        store: ImgurStore = kwargs['store']
        settings: ImgurSettings = kwargs['settings']
        super(ImgurPipe, self).set_up(channel_id, updater)
        self.store = store
        self.settings = settings
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def set_up(self, channel_id: str, updater: Updater, **kwargs):
        store: RedditStore = kwargs['store']
        settings: RedditSettings = kwargs['settings']
        self.store = store
        self.settings = settings
        super(RedditPipe, self).set_up(channel_id, updater)
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def __init__(self, channel_id: str, updater: Updater, store: RedditStore):
        super().__init__(channel_id, updater)
        self.store = store
        self.timeout = 60  # seconds
项目:musicbot    作者:ArrowsX    | 项目源码 | 文件源码
def main():
    u = Updater('YOUR-TOKEN')
    dp = u.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(MessageHandler(Filters.text, music))

    u.start_polling()
    u.idle()
项目:nekbot    作者:Nekmo    | 项目源码 | 文件源码
def __init__(self):
        self.updater = Updater(token=settings.TELEGRAM_TOKEN)
        self.dispatcher = self.updater.dispatcher
项目:Cryptocurrencies-arbitrage-algorithm    作者:coupetmaxence    | 项目源码 | 文件源码
def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater("386765167:AAEAeiO5sgg5AjlQFIw6OiYWTXr1qBeQsrE")

    # 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("begin_simple_arbitrage", begin_simple_arbitrage))
    dp.add_handler(CommandHandler("stop_simple_arbitrage", stop_simple_arbitrage))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, non_command))

    #Start scheduler
    t1 = Thread(target=ThreadFunctionScheduler, args=(updater.bot,))
    t1.start()
    # Start the Bot
    t2 = Thread(target=ThreadBot, args=(updater,))
    t2.start()

    # Run the bot 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()
项目:coolq-telegram-bot    作者:jqqqqqqqqqq    | 项目源码 | 文件源码
def run(self):
        global_vars.create_variable('mdb', MessageDB('message.db'))
        qq_bot = CQHttp(api_root=API_ROOT,
                        access_token=ACCESS_TOKEN,
                        secret=SECRET)
        global_vars.create_variable('callback_queue', queue.Queue())
        global_vars.qq_bot = qq_bot
        global_vars.tg_bot_id = int(TOKEN.split(':')[0])

        updater = Updater(TOKEN)
        global_vars.create_variable('job_queue', updater.job_queue)
        global_vars.tg_bot = updater.bot
        # Get the dispatcher to register handlers
        dp = updater.dispatcher
        global_vars.dp = dp
        dp.add_error_handler(error)

        updater.start_polling(poll_interval=1.0, timeout=200)

        threaded_server = threading.Thread(
            target=qq_bot.run,
            kwargs=dict(host=HOST, port=PORT),
            daemon=True)
        threaded_server.start()

        import plugins  # load all plugins

        while True:
            utils.from_main_thread_blocking()
            time.sleep(1)

        # 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()
项目:UnivaqBot    作者:StefanoMartella    | 项目源码 | 文件源码
def main():
    token = os.environ['TELEGRAMBOT']
    updater = Updater(token)
    dp = updater.dispatcher

    #Filling data structures.
    disim_news.preparing_disim()
    univaq_news.preparing_univaq()
    disim_prof.preparing_prof()

    updater.job_queue.run_repeating(disim_news.check_disim_news, 150)
    updater.job_queue.run_repeating(univaq_news.check_univaq_news, 150)

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("disim", disim_news.show_disim_news, pass_args=True))
    dp.add_handler(CommandHandler("disimon", disim_news.disimon))
    dp.add_handler(CommandHandler("disimoff", disim_news.disimoff))
    dp.add_handler(CommandHandler("evidenza", univaq_news.evidenza))
    dp.add_handler(CommandHandler("ultimissime", univaq_news.ultimissime))
    dp.add_handler(CommandHandler("univaqon", univaq_news.univaqon))
    dp.add_handler(CommandHandler("univaqoff", univaq_news.univaqoff))
    dp.add_handler(CommandHandler("prof", disim_prof.prof))
    dp.add_handler(CommandHandler("segreteria", disim_secretary.secretary))
    dp.add_handler(CommandHandler("mensa", univaq_general.canteen))
    dp.add_handler(CommandHandler("adsu", univaq_general.adsu))
    dp.add_handler(CommandHandler("feedback", administrator_commands.feedback))
    dp.add_handler(CommandHandler("send", administrator_commands.send, pass_args=True))
    dp.add_handler(CommandHandler("notify", administrator_commands.notify, pass_args=True))

    updater.start_polling()
    updater.idle()
项目:freqtrade    作者:gcarq    | 项目源码 | 文件源码
def init(config: dict) -> None:
    """
    Initializes this module with the given config,
    registers all known command handlers
    and starts polling for message updates
    :param config: config to use
    :return: None
    """
    global _UPDATER

    _CONF.update(config)
    if not is_enabled():
        return

    _UPDATER = Updater(token=config['telegram']['token'], workers=0)

    # Register command handler and start telegram message polling
    handles = [
        CommandHandler('status', _status),
        CommandHandler('profit', _profit),
        CommandHandler('balance', _balance),
        CommandHandler('start', _start),
        CommandHandler('stop', _stop),
        CommandHandler('forcesell', _forcesell),
        CommandHandler('performance', _performance),
        CommandHandler('count', _count),
        CommandHandler('help', _help),
        CommandHandler('version', _version),
    ]
    for handle in handles:
        _UPDATER.dispatcher.add_handler(handle)
    _UPDATER.start_polling(
        clean=True,
        bootstrap_retries=-1,
        timeout=30,
        read_latency=60,
    )
    logger.info(
        'rpc.telegram is listening for following commands: %s',
        [h.command for h in handles]
    )
项目:ToolsProject    作者:erlinux    | 项目源码 | 文件源码
def send2Channel(messages=None):
    updater = Updater(token=token)
    bot = telegram.Bot(token=token)
    jober = updater.job_queue
    dispatcher = updater.dispatcher
    bot.send_message(channel,str(messages))