當前位置: 首頁>>代碼示例>>Python>>正文


Python botapi.TelegramBot類代碼示例

本文整理匯總了Python中twx.botapi.TelegramBot的典型用法代碼示例。如果您正苦於以下問題:Python TelegramBot類的具體用法?Python TelegramBot怎麽用?Python TelegramBot使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了TelegramBot類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: setupBot

def setupBot(apitoken):
    """
    Setup the bot
    """
    bot = TelegramBot(apitoken)
    bot.update_bot_info().wait()
    return bot
開發者ID:realraum,項目名稱:r3bot-telegram,代碼行數:7,代碼來源:sample.py

示例2: start

	def start(self):
		self.logger.info("%s started" % self.serviceName)
		self.retrieveHomeSettings()

		if (self.botToken is None):
			self.logger.error ("The Telegram Token is not valid")
			self.stop()
		else:
			self.bot = TelegramBot(self.botToken)
			self.homeUpdateThread = Thread (target = self.homeUpdate)
			self.homeUpdateThread.start()

			# serving clients
			try:
				while self.isRunning:
					try:
					#The get_updates method returns the earliest 100 unconfirmed updates
						updates = self.bot.get_updates(offset = self.lastUpdateID + 1).wait()
						if (updates is not None):
							cont1=len(updates)
							if cont1 != 0:
								replyThread = Thread (target = self.reply, args=[updates[-1]])
								replyThread.start()
								self.lastUpdateID = updates[-1].update_id

						time.sleep(1)
					except Exception, e:
						self.logger.error('Something wrong occurred in telegram communication: %s. restoring the bot' % (e))
						self.bot = TelegramBot(self.botToken)
						
			except KeyboardInterrupt:
				self.stop()
開發者ID:eduman,項目名稱:smartHome2,代碼行數:32,代碼來源:TelegramService.py

示例3: __init__

class NotificationSender:
    def __init__(self, bot_token, user_id):
        self.bot = TelegramBot(bot_token)
        self.user_id = user_id

    def send_message(self, message):
        self.bot.send_message(self.user_id, message).wait()
開發者ID:Cs4r,項目名稱:weather_alarm,代碼行數:7,代碼來源:sender.py

示例4: main

def main():
    last_post_date, tgm_data = load_settings()

    rss = feedparser.parse(settings.RSS_URL)

    logging.debug("last_post_date: %s", last_post_date.isoformat())
    # find new entries in feed
    new_entries = []
    for entry in rss.entries:
        try:
            entry_published = datetime.utcfromtimestamp(
                calendar.timegm(entry.published_parsed))
            if entry_published > last_post_date:
                new_entries.append(entry)
        except AttributeError as e:
            logging.error("%s\n%s", e, entry)

    logging.info('The number of new entries: %s\nEntries: %s',
                 len(new_entries),
                 [(item.get('id'), item.get('published_parsed')) for item in
                  new_entries])

    date = datetime.now()
    if not new_entries:
        logging.info('New entries are not found')
        save_settings(date.isoformat())
        return

    # sort new entries by published date
    new_entries.sort(key=lambda item: item.published_parsed)

    # send to telegram channel
    tgm_bot = TelegramBot(settings.TGM_BOT_ACCESS_TOKEN)
    for entry in new_entries:
        try:

            logging.debug("Raw message:\n%s\n", entry.description)
            text = entry.title + '\n\n' + entry.link + '\n\n' + entry.description
            message = remove_tags(text)
            logging.debug("message:\n%s\n", message)
        except AttributeError as e:
            logging.error("%s\n%s", e, entry)
            continue

        answer = tgm_bot.send_message(settings.TGM_CHANNEL, message).wait()
        if isinstance(answer, twx.botapi.Error):
            logging.error("error code: %s\nerror description: %s\n",
                          answer.error_code,
                          answer.description)
            break
        else:
            date = max(
                datetime.utcfromtimestamp(
                    calendar.timegm(entry.published_parsed)),
                date
            )

        time.sleep(1)

    save_settings(date.isoformat())
開發者ID:PyNSK,項目名稱:RSS2Telegram,代碼行數:60,代碼來源:bot.py

示例5: MessageServer

class MessageServer(object):
    def __init__(self):
        self.thread_map = {}
        self.bot = TelegramBot(API_TOKEN)
        self.updates = set(self.bot.get_updates().wait())

    def poll(self):
        while True:
            del_list = []
            for name in self.thread_map:
                thread = self.thread_map[name]
                if thread.finished_event.isSet():
                    del_list.append(name)
            for x in del_list:
                del self.thread_map[x]
            print("<{time}> Waiting....".format(time=datetime.now().time()))
            updates = set(self.bot.get_updates().wait())
            new_updates = updates.difference(self.updates)
            for update in new_updates:
                print("<{time}> Received new message....".format(time=datetime.now().time()))
                user = update.message.sender.id
                if user in self.thread_map:
                    print("<{time}> Dispatching message to thread....".format(time=datetime.now().time()))
                    self.thread_map[user]._add_to_queue(update.message.text)
                else:
                    print("<{time}> Creating new thread....".format(time=datetime.now().time()))
                    user_thread = Worker(user)
                    self.thread_map[user] = user_thread
                    print("<{time}> Dispatching message to thread....".format(time=datetime.now().time()))
                    user_thread._add_to_queue(update.message.text)
                self.updates.add(update)
開發者ID:Ahuge,項目名稱:TelegramBot,代碼行數:31,代碼來源:v2.py

示例6: main

def main():
    try:
        with open('API_KEY', 'r') as f:
            api_key = f.read().replace('\n', '')
    except IOError:
        print "please write the api key in file `API_KEY`"
        exit(1)

    bot = TelegramBot(api_key)
    bot.update_bot_info().wait()
    print(bot.username)

    last_update_id = int(0)
    while True:
        try:
            updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
            for update in updates:
                last_update_id = update.update_id
                #print(update)
                process_update(bot, update)
        except KeyboardInterrupt:
            # Allow ctrl-c.
            raise KeyboardInterrupt
        except Exception as e:
            print "---\nException: "
            print e
            traceback.print_exc()
            pass
開發者ID:auzias,項目名稱:pikon,代碼行數:28,代碼來源:main.py

示例7: pub_to_telegram

def pub_to_telegram(text, bot_token, tg_channel):
    tgm_bot = TelegramBot(bot_token)
    answer = tgm_bot.send_message(tg_channel, text).wait()
    if isinstance(answer, twx.botapi.Error):
        print('error code: %s\nerror description: %s\n',
              answer.error_code,
              answer.description)
    else:
        print('OK')
開發者ID:pythondigest,項目名稱:pythondigest,代碼行數:9,代碼來源:pub_digest.py

示例8: start

def start():
 bot = TelegramBot(token)
 bot.update_bot_info().wait()
 print(bot.username)
 #foto belle -33909375 
 #user_id = int(23263342)

 #result = bot.send_message(user_id, 'Salve ragazzi').wait()
 #XXX WebHook automatico non funzionante
 result = bot.set_webhook(token)
 print('*****Il risultato:' % (result))
 return "ok"
開發者ID:kmos,項目名稱:cosbytbot,代碼行數:12,代碼來源:flaskapp.py

示例9: send_telegram

def send_telegram(pdf):
    """
    Отсылается сообщение через telegram bot. Получатель определяется по полю user.employee.sms_notify
    :param pdf:
    :return:
    """
    d = shelve.open('shelve.db')
    import_mode = d['IMPORT_MODE']
    d.close()

    logger.info('')
    logger.info('――> Telegram:')

    if import_mode:
        logger.info('····skip due import mode')
        return None

    if pdf.upload_to_ctpbureau_status:

        if pdf.ctpbureau.name == 'Admin':
            # TODO прибито гвоздями; можно сделать в настройках что-то вроде, - пропускать, если есть стоп-слова в названии. Но опять таки - что пропускать? Аплоад? Смс? Нотификации? Если все пропускать, тогда дебажить не получится
            # debugging purpose; if outputter is Admin then telegram send only to first superuser
            receivers = Employee.objects.filter(user__is_superuser=True)
        else:
            receivers = Employee.objects.filter(telegram_notify=True)

        for each in receivers:

            telegram_id = each.telegram_id
            bot = TelegramBot(settings.TELEGRAM_API_KEY)

            message = """
№{} {}
Плит: {}, Машина: {}, Вывод: {}
""".format(pdf.order, pdf.ordername, str(pdf.plates),pdf.machines[1].name, pdf.ctpbureau.name)

            # logger.debug('telegram_id={}'.format(telegram_id))
            # logger.debug('username={}'.format(each.user.username))

            responce = bot.send_message(chat_id=telegram_id, text=message).wait()

            if isinstance(responce, twx.botapi.botapi.Message):
                logger.info('··· {} receive notify'.format(responce.chat.username))
            elif isinstance(responce, twx.botapi.botapi.Error):
                logger.error(responce)
            else:
                logger.error('Critical telegram twx bug:')
                logger.error(responce)

    else:
        # если по какой-то причине у нас не софрмирован upload_to_ctpbureau_status
        logger.warning('····telegram NOT sent. Reason: failed upload')
開發者ID:swasher,項目名稱:pdfupload,代碼行數:52,代碼來源:action.py

示例10: TelegramBroadcaster

class TelegramBroadcaster():
    """
    Setup the bot
    """
    def __init__(self):
        self.bot = TelegramBot('<BOT_KEY>')
        self.bot.update_bot_info().wait()
        self.user_id = int(<CHANNEL_KEY>) # channel goyanglib
        print(self.bot.username)

    def send(self, message):
        result = self.bot.send_message(self.user_id, message).wait()
        print(result)
開發者ID:wooyeong,項目名稱:goyanglib,代碼行數:13,代碼來源:goyanglib.py

示例11: __init__

 def __init__(self):
     self.bot = TelegramBot(self.token)
     self.bot.get_me()
     last_updates = self.bot.get_updates(offset=0).wait()
     try:
         self.last_update_id = list(last_updates)[-1].update_id
     except IndexError:
         self.last_update_id = None
     print('last update id: {0}'.format(self.last_update_id))
開發者ID:moskmax,項目名稱:nim_telegrambot,代碼行數:9,代碼來源:nimbot.py

示例12: __init__

    def __init__(self, token, bot_id, my_user):
        self.token = token.strip()
        self.bot_id = int(bot_id)
        self.my_user = int(my_user)

        self.bot = TelegramBot(self.token)
        self.bot.update_bot_info().wait()

        self.queue = deque()
        self.offset = 0  # Needed for the bot.get_updates method to avoid getting duplicate updates
開發者ID:ricgu8086,項目名稱:vAlfred-2.0,代碼行數:10,代碼來源:AdapterTelegram2Channel.py

示例13: __init__

    def __init__(self, config, interpreter):
        super().__init__()
        self.__interpreter = interpreter
        self.__logger = logging.getLogger('telegram')
        logHandler = StreamHandler()
        logHandler.setLevel(logging.DEBUG)
        self.__logger.addHandler(logHandler)

        self.__bot = TelegramBot(config['Telegram']['token'])
        self.__logger.warning("Bot details: " + str(self.__bot.get_me().wait()))

        self.__updateOffset = None
開發者ID:rpoisel,項目名稱:willhaben_notify,代碼行數:12,代碼來源:telegram.py

示例14: Telegram

class Telegram(object):
    def __init__(self, config, interpreter):
        super().__init__()
        self.__interpreter = interpreter
        self.__logger = logging.getLogger('telegram')
        logHandler = StreamHandler()
        logHandler.setLevel(logging.DEBUG)
        self.__logger.addHandler(logHandler)

        self.__bot = TelegramBot(config['Telegram']['token'])
        self.__logger.warning("Bot details: " + str(self.__bot.get_me().wait()))

        self.__updateOffset = None

    def send_msg(self, telegram_id, text):
        self.__bot.send_message(telegram_id, text).wait()

    def getUpdates(self, dbSession):
        updates = None
        try:
            if self.__updateOffset is not None:
                updates = self.__bot.get_updates(offset=self.__updateOffset + 1).wait()
            else:
                updates = self.__bot.get_updates().wait()

            if updates is None:
                raise Exception("No updates have been received due to an error")
        except:
            return

        for update in updates:
            if hasattr(update, 'message'):
                self.__logger.warning(str(update.message.sender) + ": " + update.message.text)
                self.__interpreter.interpret(dbSession, self, update.message.sender, update.message.text.split(' '))
            if hasattr(update, 'update_id'):
                self.__updateOffset = update.update_id

    def shutdown(self):
        pass
開發者ID:rpoisel,項目名稱:willhaben_notify,代碼行數:39,代碼來源:telegram.py

示例15: main

def main():
    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    cool_answers_raw = config.get('phrases', 'cool_answers')
    cool_answers = [ answer for answer in cool_answers_raw.split('"') if answer and answer!=',']

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Connecting bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()
    print '\tBot connected! Bot name: %s' % bot.username

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()

            for update in updates:
                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    #text = regex.sub('', text)
                    words = text.split()

                    for word in words:
                        # Process commands:
                        if 'http://' in word or 'https://' in word:
                            # Get a random answer phrase:
                            answer = random.choice(cool_answers)
                            bot.send_message(chat_id, answer)

        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
            raise
開發者ID:victordiaz,項目名稱:telegram-bots,代碼行數:58,代碼來源:BotBQ.py


注:本文中的twx.botapi.TelegramBot類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。