• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python telegram.Bot类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: join

def join(bot: Bot, update):
    """Unisciti a una partita."""
    game = findgamebyid(update.message.chat.id)
    # Nessuna partita in corso
    if game is None:
        bot.sendMessage(update.message.chat.id, s.error_no_games_found, parse_mode=ParseMode.MARKDOWN)
        return
    # Fase di join finita
    if game.phase != 'Join':
        game.message(s.error_join_phase_ended)
        return
    p = game.findplayerbyid(update.message.from_user['id'])
    # Giocatore già in partita
    if p is not None:
        game.message(s.error_player_already_joined)
        return
    # Giocatore senza username
    if update.message.from_user.username is None:
        game.message(s.error_no_username)
        return
    p = Player(game, update.message.from_user.id, update.message.from_user.username)
    try:
        p.message(s.you_joined.format(game=game.name, adminname=game.admin.tusername if game.admin is not None else p.tusername))
    except Unauthorized:
        # Bot bloccato dall'utente
        game.message(s.error_chat_unavailable)
        return
    # Aggiungi il giocatore alla partita
    game.joinplayer(p)
    # Salva
    game.save()
开发者ID:Steffo99,项目名称:royal-mifia,代码行数:31,代码来源:main.py


示例2: register_webhooks

def register_webhooks(force=False):
    global BOTS_REGISTERED
    if BOTS_REGISTERED and not force:
        return

    BOTS_REGISTERED = {}

    for bot_config in settings.TELEGRAM_BOT:
        bot = Bot(bot_config['token'])

        if 'webhook' in bot_config:
            url = bot_config['webhook'] % bot.token
            if url[-1] != '/':
                url += '/'
        else:
            webhook = reverse('telegram_webhook', kwargs={'token': bot.token})
            from django.contrib.sites.models import Site
            current_site = Site.objects.get_current()
            url = 'https://' + current_site.domain + webhook

        bot.set_webhook(url)
        bot = Bot(bot_config['token'])
        dispatcher = DjangoDispatcher(bot)
        register = import_string(bot_config['register'])
        register(dispatcher)
        BOTS_REGISTERED[bot.token] = dispatcher
        logger.info('bot %s registered on url %s', bot.token, url)
开发者ID:ebertti,项目名称:python-telegram-bot,代码行数:27,代码来源:django.py


示例3: set_phpsessid

def set_phpsessid(bot: telegram.Bot, update: telegram.Update):
    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    try:
        state = State(bot, chat_id, user_id, phpsessid_conversation,
                      phpsessid_done)
        state['command'] = update.message.text
        state['from'] = update.message.from_user.name
        message = 'stap 1: login op jotihunt.net\n ' \
                  'stap2: zoek uit hoe je cookies van jothunt.net uitleest in je browser. \n ' \
                  'stap 3: ga op zook naar de cookie met de naam PHPSESSID.\n  ' \
                  'stap 4: plak de waarde hier om de cookie te  verversen van de bot.\n' \
                  ' of /cancel om te stoppen'
        bot.sendMessage(chat_id, message,
                        reply_to_message_id=update.message.message_id)
    # TODO add a keyboard
        Updates.get_updates().botan.track(update.message, 'phpsessid')
    except MultipleConversationsError:
        bot.sendMessage(chat_id, "Er is al een commando actief je kunt dit "
                                 "commando niet starten.\n"
                                 " type /cancel om het vorige commando te "
                                 "stoppen te stoppeny",
                        reply_to_message_id=update.message.message_id)
        Updates.get_updates().botan.track(update.message,
                                          'incorrect_phpsessid')
开发者ID:RSDT,项目名称:bot2,代码行数:25,代码来源:commands.py


示例4: start

def start(bot: Bot, update: Update):
    users_handler(bot, update)
    message: Message = update.message
    with menus_lock:
        if message.chat_id not in menus:
            menus[message.chat_id] = Menu()
        else:
            # todo remove old keyboard and replace with the new one?
            pass
        menu = menus[message.chat_id]
    api = RpApi.get_instance(settings.Settings().rp_username, settings.Settings().rp_pass)
    response = api.get_telegram_link(update.effective_user.id)
    rp_acc = response.data
    if rp_acc is None:
        user: User = update.effective_user
        api.send_telegram_user(user.id, user.first_name, user.last_name, user.username)
        bot.send_message(update.effective_chat.id, 'Je telegram account is nog niet gelinkt.'
                                                   'Vraag aan de homebase of ze dat willen doen. '
                                                   'En zeg daarna /start.',
                         reply_to_message_id=update.effective_message.message_id)
    text, buttons = menu.get_next_buttons(update, '0', rp_acc)
    keyboard = [[button] for button in buttons]
    reply_markup = InlineKeyboardMarkup(keyboard)
    if update.effective_chat.type == Chat.PRIVATE:
        keyboard = ReplyKeyboardMarkup([[KeyboardButton('/start met het laten zien van het menu')]
                                   , [KeyboardButton('verstuur hunter locatie', request_location=True)]])
    else:
        keyboard = ReplyKeyboardMarkup([])
    bot.send_message(update.effective_chat.id, welcome_message, reply_markup=keyboard)
    message.reply_text(text, reply_markup=reply_markup)
开发者ID:RSDT,项目名称:bot2,代码行数:30,代码来源:menu.py


示例5: bug

def bug(bot: telegram.Bot, update: telegram.Update):
    """

                :param bot:
                :param update:
                :return:
                """
    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    try:
        state = State(bot, chat_id, user_id, bug_conversation, bug_done)
        state['command'] = update.message.text
        state['from'] = update.message.from_user.name
        keyboard = telegram.ReplyKeyboardMarkup([['app'], ['site'],
                                                 ['anders']])
        bot.sendMessage(chat_id, "Waar wil je een tip of een top voor "
                                 "sturen?\napp/bot/site/anders",
                        reply_to_message_id=update.message.message_id,
                        reply_markup=keyboard)
        Updates.get_updates().botan.track(update.message, 'bug')
    except MultipleConversationsError:
        bot.sendMessage(chat_id, "Er is al een commando actief je kunt dit "
                                 "commando niet starten.\n"
                                 " type /cancel om het vorige commando te "
                                 "stoppen te stoppen",
                        reply_to_message_id=update.message.message_id)
        Updates.get_updates().botan.track(update.message, 'incorrect_bug')
开发者ID:RSDT,项目名称:bot2,代码行数:27,代码来源:commands.py


示例6: delete

def delete(bot: Bot, update: Update):
    if not DELETE:
        return

    global data_set
    chat_id = update.message.chat_id
    user = data_set.participants[update.message.chat_id]
    user.active_ = False
    user.delete_participant()

    try:
        os.remove('survey/data_incomplete/' + str(user.chat_id_) + '.csv')
    except OSError:
        pass

    try:
        os.remove('survey/data_complete/' + str(user.chat_id_) + '.csv')
    except OSError:
        pass

    del data_set.participants[update.message.chat_id]
    try:
        bot.send_message(chat_id=chat_id, text="Successfully deleted DB entry and user data. To restart enter /start")
    except TelegramError as error:
        if error.message == 'Unauthorized':
            user.pause()
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:26,代码来源:diary-survey-bot.py


示例7: help_command

def help_command(bot: telegram.Bot, update: telegram.Update):
    message = start_message + "\n\n"
    for commando in CommandHandlerWithHelp.helps:
        message += '/' + commando + ' - ' + CommandHandlerWithHelp.helps[
            commando] + '\n'
    bot.sendMessage(update.message.chat_id, message)
    Updates.get_updates().botan.track(update.message, 'help')
开发者ID:RSDT,项目名称:bot2,代码行数:7,代码来源:commands.py


示例8: cancel

def cancel(bot: telegram.Bot, update: telegram.Update):
    """

    :param bot:
    :param update:
    :return:
    """
    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    h = str(user_id) + str(chat_id)
    try:
        state = State.states[h]
        state.cancel()
    except KeyError:
        kb = telegram.ReplyKeyboardHide()
        if update.message.chat_id > 0:
            keyboard = DEFAULT_KEYBOARD
            kb = telegram.ReplyKeyboardMarkup(keyboard,
                                              one_time_keyboard=False,
                                              selective=True)
        bot.sendMessage(chat_id, "Er is geen commando actief.",
                        reply_to_message_id=update.message.message_id,
                        reply_markup=kb)
        Updates.get_updates().botan.track(update.message, 'incorrect_cancel')
    else:
        kb = telegram.ReplyKeyboardHide()
        if update.message.chat_id > 0:
            keyboard = DEFAULT_KEYBOARD
            kb = telegram.ReplyKeyboardMarkup(keyboard,
                                              one_time_keyboard=False,
                                              selective=True)
        bot.sendMessage(update.message.chat_id, "Het commando is gestopt.",
                        reply_to_message_id=update.message.message_id,
                        reply_markup=kb)
        Updates.get_updates().botan.track(update.message, 'cancel')
开发者ID:RSDT,项目名称:bot2,代码行数:35,代码来源:commands.py


示例9: set_url_conversation

def set_url_conversation(bot: telegram.Bot, update: telegram.Update, state):
    s = state.get_state()
    keyboard = None
    message = 'unexpected input!!'
    if s == 0:
        if update.message.text in ['hint', 'opdracht', 'nieuws']:
            message = 'Wat is de url zonder de id?\n bijv. ' \
                      'http://www.jotihunt.net/groep/opdracht.php?MID='
            state['soort'] = update.message.text
        else:
            message = 'kies uit hint, opdracht of nieuws. of /cancel om ' \
                      'terug te gaan.'
    if s == 1:
        state['url'] = update.message.text
        s.done()
        message = 'De url is aangepast voor ' + state['soort']
    if keyboard is not None:
        kb = telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True,
                                          selective=True)
        bot.sendMessage(update.message.chat_id, message,
                        reply_to_message_id=update.message.message_id,
                        reply_markup=kb)
    else:
        kb = telegram.ReplyKeyboardHide()
        if update.message.chat_id > 0:
            keyboard = DEFAULT_KEYBOARD
            kb = telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=False,
                                              selective=True)
        bot.sendMessage(update.message.chat_id, message,
                        reply_to_message_id=update.message.message_id,
                        reply_markup=kb)
开发者ID:RSDT,项目名称:bot2,代码行数:31,代码来源:commands.py


示例10: save

def save(bot: Bot, update):
    """Salva una partita su file."""
    game = findgamebyid(update.message.chat.id)
    if game is not None:
        game.save()
    else:
        bot.sendMessage(update.message.chat.id, s.error_no_games_found, parse_mode=ParseMode.MARKDOWN)
开发者ID:Steffo99,项目名称:royal-mifia,代码行数:7,代码来源:main.py


示例11: debug

def debug(bot: Bot, update):
    """Visualizza tutti i ruoli e gli id."""
    if __debug__:
        game = findgamebyid(update.message.chat.id)
        if game is not None:
            game.revealallroles()
        else:
            bot.sendMessage(update.message.chat.id, s.error_no_games_found, parse_mode=ParseMode.MARKDOWN)
开发者ID:Steffo99,项目名称:royal-mifia,代码行数:8,代码来源:main.py


示例12: phpsessid_conversation

def phpsessid_conversation(bot: telegram.Bot, update: telegram.Update, state):
    s = state.get_state()
    if s == 0:
        state['cookie'] = update.message.text
        state.done()

        bot.sendMessage(update.message.chat_id,
                        update.message.from_user.name + ' de cookie is '
                                                        'aangepast.')
开发者ID:RSDT,项目名称:bot2,代码行数:9,代码来源:commands.py


示例13: test

def test(bot: telegram.Bot, update: telegram.Update):
    bot.sendMessage(update.message.chat_id, 'de bot is online')
    if update.message.chat_id > 0:
        url = Updates.get_updates().botan.shorten('http://google.com',
                                                  update.message.from_user.id)
    else:
        url = 'http://google.com'
    bot.sendMessage(update.message.chat_id, url)
    Updates.get_updates().botan.track(update.message, 'test')
开发者ID:RSDT,项目名称:bot2,代码行数:9,代码来源:commands.py


示例14: debugchangerole

def debugchangerole(bot: Bot, update):
    """Cambia il ruolo a un giocatore."""
    if __debug__:
        game = findgamebyid(update.message.chat.id)
        if game is not None:
            cmd = update.message.text.split(' ', 2)
            game.changerole(game.findplayerbyusername(cmd[1]), globals()[cmd[2]])
        else:
            bot.sendMessage(update.message.chat.id, s.error_no_games_found, parse_mode=ParseMode.MARKDOWN)
开发者ID:Steffo99,项目名称:royal-mifia,代码行数:9,代码来源:main.py


示例15: error

def error(bot, update, error):
    try:
        ch_id = "27002116"
        starter = Bot(token=token)
        txt = "An error happened"
        starter.sendMessage(ch_id, text=txt)
    except:
        pass
    logger.warn('Update "%s" caused error "%s"' % (update, error))
开发者ID:mikexine,项目名称:UnipdBot,代码行数:9,代码来源:bot.py


示例16: load

def load(bot: Bot, update):
    """Carica una partita salvata."""
    game = findgamebyid(update.message.chat.id)
    if game is not None:
        bot.sendMessage(update.message.chat.id, s.error_game_in_progress, parse_mode=ParseMode.MARKDOWN)
        return
    file = open(str(update.message.chat.id) + ".p", "rb")
    game = pickle.load(file)
    inprogress.append(game)
    game.message(s.game_loaded)
开发者ID:Steffo99,项目名称:royal-mifia,代码行数:10,代码来源:main.py


示例17: endjoin

def endjoin(bot: Bot, update):
    """Termina la fase di join e inizia quella di votazione."""
    game = findgamebyid(update.message.chat.id)
    if game is not None and game.phase == 'Join':
        if update.message.from_user.id == game.admin.tid:
            game.message(s.join_phase_ended)
            game.startpreset()
        else:
            game.message(s.error_not_admin)
    else:
        bot.sendMessage(update.message.chat.id, s.error_no_games_found, parse_mode=ParseMode.MARKDOWN)
开发者ID:Steffo99,项目名称:royal-mifia,代码行数:11,代码来源:main.py


示例18: start

def start(bot: telegram.Bot, update: telegram.Update):
    if update.message.chat_id > 0:
        keyboard = telegram.ReplyKeyboardMarkup(DEFAULT_KEYBOARD,
                                                one_time_keyboard=False)
        bot.sendMessage(update.message.chat_id, start_message,
                        reply_markup=keyboard)
    else:
        bot.sendMessage(update.message.chat_id, start_message)
    x = authenticate()
    x(lambda bot2, update2: print('authenticated:\n' + str(update.to_dict(
    ))))(bot, update)
    Updates.get_updates().botan.track(update.message, 'start')
开发者ID:RSDT,项目名称:bot2,代码行数:12,代码来源:commands.py


示例19: __init__

class TelegramBotAlert:


    def __init__(self):
        self.model = Model()
        config = configparser.ConfigParser()
        config.read('settings.ini')

        self.__list_of_chat_ids = self.model.get_chat_ids()
        self.__token = config.get("TELEGRAM", "token")
        self.__bot = Bot(token=self.__token)

    def create_alert_message(self, list_of_alredy_online_hosts, list_of_offline_hosts):
        message = ""

        if len(list_of_alredy_online_hosts) > 0:
            serialize_list_of_alredy_online_hosts = create_serialize_list_of_hosts(list_of_alredy_online_hosts)
            message += self.create_alert_message_with_alredy_online_hosts(serialize_list_of_alredy_online_hosts)

        if len(list_of_offline_hosts) > 0:
            serialize_list_of_offline_hosts = create_serialize_list_of_hosts(list_of_offline_hosts)
            message += self.create_alert_message_with_offline_hosts(serialize_list_of_offline_hosts)
        else:
            message += "Все узлы доступны."

        self.send_message(message)

    def create_alert_message_with_offline_hosts(self, list_of_hosts):
        message = "<b>Следующие узлы недоступны!</b>\n"
        for group in list_of_hosts:
            message += "\tГруппа: <i>{group_name}</i>\n".format(group_name=group)
            for host in list_of_hosts[group]:
                message += "\t\t{host}, {hostip}\n".format(host=host.get_name(), hostip=host.get_ip())
            message += "\n"
        return message

    def create_alert_message_with_alredy_online_hosts(self, list_of_hosts):
        message = "<b>Следующие узлы снова доступны:</b>\n"
        for group in list_of_hosts:
            message += "\tГруппа: <i>{group_name}</i>\n".format(group_name=group)
            for host in list_of_hosts[group]:
                message += "\t\t{host}, {hostip}\n".format(host=host.get_name(), hostip=host.get_ip())
            message += "\n"
        return message

    def send_message(self, message, send_to="All"):
        if send_to == "All":
            for chat_id in self.__list_of_chat_ids:
                self.__bot.send_message(chat_id=str(chat_id), text=message, parse_mode=ParseMode.HTML)
        else:
            self.__bot.send_message(chat_id=str(send_to), text=message, parse_mode=ParseMode.HTML)
开发者ID:shirolapov,项目名称:NetworkTester,代码行数:51,代码来源:bot.py


示例20: stop

def stop(bot: Bot, update: Update):
    global data_set
    chat_id = update.message.chat_id
    user = data_set.participants[update.message.chat_id]
    user.pause()
    try:
        message = STOP_TEXT[user.language_]
        bot.send_message(chat_id=chat_id, text=message, reply_markup=ReplyKeyboardRemove())
    except KeyError:
        message = STOP_TEXT[DEFAULT_LANGUAGE]
        bot.send_message(chat_id=chat_id, text=message, reply_markup=ReplyKeyboardRemove())
    except TelegramError as error:
        if error.message == 'Unauthorized':
            user.pause()
开发者ID:philippfeldner,项目名称:diary-survey-bot,代码行数:14,代码来源:diary-survey-bot.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python telegram.InlineKeyboardMarkup类代码示例发布时间:2022-05-27
下一篇:
Python util.is_string函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap