【问题标题】:How to store the contact's phone number in memory in ChatBot using python-telegram-bot如何使用 python-telegram-bot 将联系人的电话号码存储在 ChatBot 的内存中
【发布时间】:2020-04-14 21:39:15
【问题描述】:

我正在与python-telegram-bot 一起构建菜单系统。

我创建了一个Django项目,如下图,使用Webhook连接Telegram。

发送第一条消息时,我会询问联系人的电话号码,然后 保留这个号码,这样我就不需要在对话中的下一条消息中询问它, 但它不起作用。 我试图将它存储在 request.session 中,但显然每条新消息都是一个新会话,所以我丢失了号码。

我该如何解决这个问题?欢迎任何帮助。

view.py

import json
from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from core.message import proccess


@csrf_exempt
def event(request):
    json_telegram = json.loads(request.body)
    proccess(request, json_telegram)
    return HttpResponse()

messages.py

import telegram
from bot_webhook.settings import TOKEN
from telegram import InlineKeyboardMarkup, InlineKeyboardButton

bot = telegram.Bot(token=TOKEN)


def proccess(request, json_telegram):
    if 'login' in request.session:
        msg_options(json_telegram)

    else:
        try:
            request.session['login'] = json_telegram['message']['contact']['phone_number']
            msg_options(json_telegram)

        except BaseException:
            msg_login(json_telegram)


def msg_login(json_telegram):
    chat_id = json_telegram['message']['from']['id']
    reply_markup = telegram.ReplyKeyboardMarkup(
        [[telegram.KeyboardButton('Click to Login', request_contact=True)]],
        resize_keyboard=True,
        one_time_keyboard=True
    )
    bot.sendMessage(chat_id, 'I need to authorize your access.', reply_markup=reply_markup)


def msg_options(json_telegram):
    chat_id = json_telegram['message']['from']['id']
    first_name = json_telegram['message']['from']['first_name']
    last_name = json_telegram['message']['from']['last_name']
    button_list = []
    button_list.append(InlineKeyboardButton('Button One', callback_data='query_one'))
    button_list.append(InlineKeyboardButton('Button two', callback_data='query_two'))
    reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2))
    bot.send_message(text='Hello {0} {1}!\nI have this options:'.format(first_name, last_name),
                     chat_id=chat_id,
                     reply_markup=reply_markup)


def build_menu(buttons,
               n_cols,
               header_buttons=None,
               footer_buttons=None):
    menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
    if header_buttons:
        menu.insert(0, [header_buttons])
    if footer_buttons:
        menu.append([footer_buttons])
    return menu

【问题讨论】:

标签: python django python-telegram-bot


【解决方案1】:

一旦我在 Api 中没有找到解决方案,我就使用了这个解决方案:

当有交互时,我检查联系人是否已经存在于我的数据库中, 如果是肯定的,我会继续谈话, 如果是否定的,我会通过共享电话来要求身份证明。 所以当我得到信息时,我将它记录在数据库中, 这样在新的交互中我可以自动识别它。

将它记录在我的数据库中是一个选项,另一个选项是作为文本存档。

如果您有更好的选择,请为我们展示。

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2017-12-01
    • 2015-05-18
    • 2017-03-28
    • 1970-01-01
    相关资源
    最近更新 更多