如何使用python中的电报机器人和电传机制作调查问卷

如何使用python中的电报机器人和电传机制作调查问卷,python,telegram-bot,telepot,Python,Telegram Bot,Telepot,在我的研究中,我想用一个电报机器人每天在一个特定的时刻向我实验的35名志愿者的个人智能手机发送4个简单的选择题。我已经查阅了telepot文档和示例,但我无法构建一个好的解决方案。测验的例子很接近,但问题和答案应该对我的志愿者可见,并写在一个简单的日志文件中进行进一步分析 这是我对quick.py的修改版本 import sys import time import random import telepot import telepot.helper from telepot.loop imp

在我的研究中,我想用一个电报机器人每天在一个特定的时刻向我实验的35名志愿者的个人智能手机发送4个简单的选择题。我已经查阅了telepot文档和示例,但我无法构建一个好的解决方案。测验的例子很接近,但问题和答案应该对我的志愿者可见,并写在一个简单的日志文件中进行进一步分析

这是我对quick.py的修改版本

import sys
import time
import random
import telepot
import telepot.helper
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.delegate import (
    per_chat_id, per_callback_query_origin, create_open, pave_event_space)

"""
$ python3.5 qst.py <token>
Send a chat message to the bot. It will give you 4 questions.
It handles callback query by their origins. All callback query originated from
the same chat message will be handled by the same `CallbackQueryOriginHandler`.
Timeout on questions is not needed. How to remove them!
"""

nameLogFile = 'qst_log.txt';

class QstStarter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(QstStarter, self).__init__(*args, **kwargs)

    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        self.sender.sendMessage(
            'Are you ready for the first question?',
            reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[[
                     InlineKeyboardButton(text='START', callback_data='start'),
                ]]
           )
        )
        self.close()  # let Qster take over

class Qster(telepot.helper.CallbackQueryOriginHandler):

    def __init__(self, *args, **kwargs):
        super(Qster, self).__init__(*args, **kwargs)
        self._cnt = 0;

    def _show_next_question(self):
        qst = ["Question 1", "Question 2", "Question 3", "Question 4"];
        choices = ["a","b","c","d","e"];

        if self._cnt<4 :
             self.editor.editMessageText(qst[self._cnt],
              reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[
                   list(map(lambda c: InlineKeyboardButton(text=str(c), callback_data=str(c)), choices))
                ]
              )
            )

    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')

        if query_data != 'start':
             # log this answer: Question is this tread safe!
             self._f = open(nameLogFile, 'a+');
             self._f.write(str(from_id) + ',' + str(msg["message"]["edit_date"]) + ',' + \
             repr(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(msg["message"]["edit_date"]))) + ',' + \
             str(self._cnt) + ',' + repr(msg["message"]["text"]) + ',' + repr(query_data) + '\n');
             self._f.close();
             # show this answer
             bot.sendMessage(from_id, msg["message"]["text"] + " " + query_data, parse_mode='HTML');

             self._cnt += 1

        if self._cnt<4 :
            self._show_next_question()
        else :
            self.editor.editMessageText('\nThanks', reply_markup=None);


    def on__idle(self, event):
             #self.close()


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, QstStarter, timeout=3),
    pave_event_space()(
        per_callback_query_origin(), create_open, Qster, timeout=10),
])

MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
   time.sleep(10)
导入系统 导入时间 随机输入 进口电传机 导入telepot.helper 从telepot.loop导入MessageLoop 从telepot.namedtuple导入InlineKeyboardMarkup,InlineKeyboardButton 从telepot.delegate导入( 按聊天id、按回调查询来源、创建打开、铺设事件空间) """ $python3.5qst.py 向机器人发送聊天信息。它会给你4个问题。 它按其来源处理回调查询 相同的聊天信息将由相同的“CallbackQueryOriginHandler”处理。 问题不需要超时。如何删除它们! """ nameLogFile='qst_log.txt'; 类QstStarter(telepot.helper.ChatHandler): 定义初始化(self,*args,**kwargs): 超级(QstStarter,self)。\uuuuu初始值(*args,**kwargs) 聊天信息中的def(self,msg): 内容类型,聊天类型,聊天id=telepot.glance(msg) self.sender.sendMessage( “你准备好回答第一个问题了吗?”, reply_markup=InlineKeyboardMarkup( 内联键盘=[[ InlineKeyboardButton(text='START',callback_data='START'), ]] ) ) self.close()#让Qster接管 类Qster(telepot.helper.CallbackQueryOriginHandler): 定义初始化(self,*args,**kwargs): 超级(Qster,self)。\uuuuu初始值(*args,**kwargs) 自身._cnt=0; 定义显示下一个问题(自我): qst=[“问题1”、“问题2”、“问题3”、“问题4”]; 选项=[“a”、“b”、“c”、“d”、“e”]; 如果是自己的话。 您可以通过调度器调用任何函数,如
ADScheduler
或许多其他函数

另外,更简单的方法是使用
python电报bot
模块,其中包括
ConversationHandler
方法

因此,您只需通过调度程序运行
entry\u point
函数,就可以获得快乐


其他设备
telepot
也支持此操作,但更硬更脏。是吗?

如果您发布到目前为止尝试过的代码及其存在的具体问题,您可能会获得更好的结果。您可能想回顾这篇文章:嗨,Aron,我添加了我的quick.py示例的改编版本。