当前位置: 首页>>代码示例>>Python>>正文


Python Bot.getUpdates方法代码示例

本文整理汇总了Python中telegram.Bot.getUpdates方法的典型用法代码示例。如果您正苦于以下问题:Python Bot.getUpdates方法的具体用法?Python Bot.getUpdates怎么用?Python Bot.getUpdates使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telegram.Bot的用法示例。


在下文中一共展示了Bot.getUpdates方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check_updates

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
    def check_updates(b: telegram.Bot, update_id: int) -> int:

        for update in b.getUpdates(
                offset=update_id,
                timeout=INTERVAL,
        ):
            message = update.message.text
            upd_chat_id = update.message.chat_id
            update_id = update.update_id + 1
            cmd = message.lower()

            if upd_chat_id in CHAT_ID:
                # commands list

                if '/ping' in cmd:
                    send('Pong!', ch_id=upd_chat_id)

                elif 'сиськ' in cmd or '/boobs' in cmd:
                    bot.sendPhoto(chat_id=upd_chat_id, photo=get_boobs_url())

                elif 'жоп' in cmd or '/ass' in cmd:
                    bot.sendPhoto(chat_id=upd_chat_id, photo=get_butts_url())

                elif 'курс' in cmd or 'currency' in cmd:
                    send(msg=get_currency(), ch_id=upd_chat_id)

                elif '/ver' in cmd:
                    send(msg=VERSION, ch_id=upd_chat_id)

            else:
                pass

        return update_id
开发者ID:vlmonk,项目名称:SpongeBot,代码行数:35,代码来源:bot_d.py

示例2: telegram_poller

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
def telegram_poller(data, check_id):
    if 'token' not in data:
        util.die('checks.telegram_poller: missing token')

    token = data['token']
    update_id = int(extract(data, 'update_id', 0))

    from telegram import Bot
    from common.sql import getdb
    import urlparse
    import urllib

    db = getdb()

    bot = Bot(token)
    if not bot: return { 'status' : 'fail' }
    updates = bot.getUpdates(offset = update_id)
    for update in updates:
        if int(update.update_id) >= update_id: update_id = int(update.update_id)
        chat_id =  update.message.chat_id
        if '/' in update.message.text and ' ' in update.message.text:
            cmd, msg_data = update.message.text.split(' ', 1)
            if cmd == '/start':
                contact = db.getOne('contacts', '*', ('id = %s', msg_data))
                if contact:
                    data_decoded = urlparse.parse_qs(contact.data)
                    data_decoded['token'] = data_decoded['token'][0]
                    data_decoded['chat_id'] = chat_id
                    data_encoded = urllib.urlencode(data_decoded)
                    db.update('contacts', dict(data = data_encoded), ('id = %s', [ contact.id ]))
                    db.commit()

    check = db.getOne('checks', '*', ('id = %s', [ check_id] ))
    check_data = urlparse.parse_qs(check.data)
    check_data = urllib.urlencode(dict( token = check_data['token'][0], update_id = update_id + 1))
    db.update('checks', dict( data = check_data ), ('id = %s', [ check_id ]))
    db.commit()
    return {'status': 'success'}
开发者ID:ZUNbado,项目名称:pybearmon,代码行数:40,代码来源:checks.py

示例3: token

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
class Updater:
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. It's
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (Optional[str]): The bot's token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
        bot (Optional[Bot]):
        job_queue_tick_interval(Optional[float]): The interval the queue should
            be checked for new tasks. Defaults to 1.0

    Raises:
        ValueError: If both `token` and `bot` are passed or none of them.
    """

    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 job_queue_tick_interval=1.0):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            self.bot = Bot(token, base_url)
        self.update_queue = UpdateQueue()
        self.job_queue = JobQueue(self.bot, job_queue_tick_interval)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(self.bot, self.update_queue, workers,
                                     self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""

    def start_polling(self, poll_interval=0.0, timeout=10, network_delay=2,
                      clean=False):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling
                updates from Telegram in seconds. Default is 0.0
            timeout (Optional[float]): Passed to Bot.getUpdates
            network_delay (Optional[float]): Passed to Bot.getUpdates
            clean (Optional[bool]): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is
                False.

        Returns:
            Queue: The update queue that can be filled from the main thread

        """
        with self.__lock:
            if not self.running:
                self.running = True
                if clean:
                    self._clean_updates()

                # Create & start threads
                self._init_thread(self.dispatcher.start, "dispatcher")
                self._init_thread(self._start_polling, "updater",
                                  poll_interval, timeout, network_delay)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name,
                     args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
#.........这里部分代码省略.........
开发者ID:Suyashc1295,项目名称:python-telegram-bot,代码行数:103,代码来源:updater.py

示例4: __init__

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
class GoulashBot:
    def __init__(self):
        self.configuration = NbdConfiguration.get()
        self.store = NbdGoulashBotStore.get()
        self.last_update_id = 0
        self.users = {}
        self.bot = Bot(self.configuration.telegram_apikey)
        self.goulash_found = NbdGoulashFound.get()
        for update in self.bot.getUpdates():
            self.process_message(update)

    def temperature(self):
        response = requests.get("http://api.openweathermap.org/data/2.5/weather?id=3435910&units=metric&APPID=%s" % self.configuration.temperature_apikey).json()
        temps = response['main']
        return temps['temp']

    def load_data(self):
        self.last_update_id = self.store.read_last_update_id()
        self.users = self.store.read_users()

    def add_user(self, user, chat_id):
        if user not in self.users.keys():
            self.store.add_user(user, chat_id)
            self.users[user] = chat_id
            self.bot.sendMessage(chat_id=chat_id, text=("Registrado"))
        else:
            self.bot.sendMessage(chat_id=chat_id, text=("Ya estabas registrado"))

    def remove_user(self, user, chat_id):
        if user not in self.users.keys():
            self.bot.sendMessage(chat_id=chat_id, text=("No estabas registrado"))
        else:
            self.store.remove_user(user, chat_id)
            del self.users[user]
            self.bot.sendMessage(chat_id=chat_id, text=("Ya no recibirás notificaciones"))

    def unknown_command(self, user, chat_id):
        self.bot.sendMessage(chat_id=chat_id, text='unknown command')

    def process_message(self, update):
        chat_id = update.message.chat_id
        message = update.message.text
        username = str(update.message.from_user.id)

        if message:
            if message.startswith('/subscribe'):
                self.add_user(username, chat_id)
            elif message.startswith('/unsubscribe'):
                self.remove_user(username, chat_id)
            else:
                self.unknown_command(username, chat_id)

        self.last_update_id = update.update_id + 1
        self.store.save_last_update_id(self.last_update_id)

    # Correr periodicamente
    def check_for_messages(self):
        for update in self.bot.getUpdates(offset=self.last_update_id):
            self.process_message(update)

    def goulash(self):
        response = requests.get('http://latropilla.platosdeldia.com/modules.php?name=PDD&func=nick&nick=latropilla')
        body = response.text
        m = re.search(r'([^<>]*(ulash|spaetzle|speciale)[^<>]*)[^$]*(\$[.0-9]*)', body)
        return (m.group(1), m.group(3), self.temperature()) if m else None

    # Correr una vez al dia
    def reset_goulash_flag(self):
        self.goulash_found.save_found(False)

    def goulash_alert(self, found):
        for user in self.users.keys():
            self.bot.sendMessage(chat_id=self.users[user], text=self.build_message(found))

    def build_message(self, found):
        return "HAY %s (%s) [temp: %sC]!!!!" % found

    def ifttt(self, found):
        requests.post("http://maker.ifttt.com/trigger/goulash/with/key/%s" % self.configuration.ifttt_key, data={'value1': self.build_message(found)})

    # Correr periodicamente
    def check_for_goulash(self):
        if not NbdGoulashFound.get().read_found():
            found = self.goulash()
            self.goulash_found.save_found(found is not None)
            if found:
                self.ifttt(found)
                self.goulash_alert(found)
开发者ID:damdev,项目名称:goulash-bot,代码行数:90,代码来源:main.py

示例5: token

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
class Updater:
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. It's
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (str): The bots token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
    """

    def __init__(self, token, base_url=None, workers=4):

        self.bot = Bot(token, base_url)
        self.update_queue = Queue()
        self.dispatcher = Dispatcher(self.bot, self.update_queue,
                                     workers=workers)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None

    def start_polling(self, poll_interval=1.0, timeout=10, network_delay=2):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling
                updates from Telegram in seconds. Default is 1.0
            timeout (Optional[float]): Passed to Bot.getUpdates
            network_delay (Optional[float]): Passed to Bot.getUpdates

        Returns:
            Queue: The update queue that can be filled from the main thread
        """

        # Create Thread objects
        dispatcher_thread = Thread(target=self.dispatcher.start,
                                   name="dispatcher")
        event_handler_thread = Thread(target=self._start_polling,
                                      name="updater",
                                      args=(poll_interval, timeout,
                                            network_delay))

        self.running = True

        # Start threads
        dispatcher_thread.start()
        event_handler_thread.start()

        # Return the update queue so the main thread can insert updates
        return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=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 (Optional[str]): IP-Address to listen on
            port (Optional[int]): Port the bot should be listening on
            url_path (Optional[str]): Path inside url
            cert (Optional[str]): Path to the SSL certificate file
            key (Optional[str]): Path to the SSL key file

        Returns:
            Queue: The update queue that can be filled from the main thread
        """

        # Create Thread objects
        dispatcher_thread = Thread(target=self.dispatcher.start,
                                   name="dispatcher")
        event_handler_thread = Thread(target=self._start_webhook,
                                      name="updater",
                                      args=(listen, port, url_path, cert, key))

        self.running = True

        # Start threads
#.........这里部分代码省略.........
开发者ID:gisho,项目名称:python-telegram-bot,代码行数:103,代码来源:updater.py

示例6: Updater

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
class Updater(object):
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. Its
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (Optional[str]): The bot's token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
        bot (Optional[Bot]): A pre-initialized bot instance. If a pre-initizlied bot is used, it is
            the user's responsibility to create it using a `Request` instance with a large enough
            connection pool.

    Raises:
        ValueError: If both `token` and `bot` are passed or none of them.

    """
    _request = None

    def __init__(self, token=None, base_url=None, workers=4, bot=None):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            self._request = Request(con_pool_size=workers + 4)
            self.bot = Bot(token, base_url, request=self._request)
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception')
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      network_delay=5.,
                      clean=False,
                      bootstrap_retries=0):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling updates from Telegram in
            seconds. Default is 0.0

            timeout (Optional[float]): Passed to Bot.getUpdates

            network_delay (Optional[float]): Passed to Bot.getUpdates

            clean (Optional[bool]): Whether to clean any pending updates on Telegram servers before
#.........这里部分代码省略.........
开发者ID:python-telegram-bot,项目名称:python-telegram-bot,代码行数:103,代码来源:updater.py

示例7: originBot

# 需要导入模块: from telegram import Bot [as 别名]
# 或者: from telegram.Bot import getUpdates [as 别名]
def originBot():
    bot = Bot(token = TOKEN)
    print bot.getMe()
    updates = bot.getUpdates()
    print updates
    print [u.message.text for u in updates]
开发者ID:BigDipper7,项目名称:Telegram-Bot---QA-Bot,代码行数:8,代码来源:test.py


注:本文中的telegram.Bot.getUpdates方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。