How can make conversation between bot and user with telepot

▼魔方 西西 提交于 2019-12-13 02:58:35

问题


I want to create the bot with telepot that ask the users frequent questions. For example first ask 'whats your name.?' then the user reply 'user-name',then ask how old are you? and the user reply his age and ...

I had written a code for this chat between user and bot,but sometimes I am getting error. Please guide me how can I make this bot with telepot.?

I want to make conversation between bot and users with telepot


回答1:


What you're looking for is DelegatorBot. Consider this tutorial.

Consider this scenario. A bot wants to have an intelligent conversation with a lot of users, and if we could only use a single line of execution to handle messages (like what we have done so far), we would have to maintain some state variables about each conversation outside the message-handling function(s). On receiving each message, we first have to check whether the user already has a conversation started, and if so, what we have been talking about. To avoid such mundaneness, we need a structured way to maintain “threads” of conversation.

DelegatorBot provides you with one instance of your bot for every user, so you don't have to think about what happens when multiple users talk to it. (If it helps you, feel free to have a look at how I am using it.)
The tutorial's example is a simple counter of how many messages the user has sent:

import sys
import time
import telepot
from telepot.loop import MessageLoop
from telepot.delegate import pave_event_space, per_chat_id, create_open

class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0

    def on_chat_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)

TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, MessageCounter, timeout=10),
])
MessageLoop(bot).run_as_thread()

while 1:
    time.sleep(10)

This code creates an instance of MessageCounter for every individual user.

I had written a code for this chat between user and bot,but sometimes I am getting error.

If your question was rather about the errors you're getting than about how to keep a conversation with state, you need to provide more information about what errors you're getting, and when those appear.



来源:https://stackoverflow.com/questions/47267473/how-can-make-conversation-between-bot-and-user-with-telepot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!