如何使用python中的电报机器人和电视机进行问卷调查

时间:2017-08-05 14:43:54

标签: python telegram-bot telepot

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

这是我修改过的quiz.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)

我想让世界各地的志愿者一直回答这些问题,但我不知道如何驾驭事件超时。

第二个问题:如何用计时器开始问卷调查?我想在特定时刻每天向35名志愿者开一次问卷。

1 个答案:

答案 0 :(得分:1)

Denissen。 您可以通过from gcd import gcd 等调度程序调用任何函数。

使用ADScheduler模块更简单的方法,包括python-telegram-bot方法。

https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py

所以你只需要通过调度程序运行ConversationHandler函数并获得快乐。

其他服务entry_point也支持此操作,但更加困难和肮脏。不是吗?