获取request.form在文本冒险游戏中扮演raw_input(twilio)

时间:2013-10-12 02:30:00

标签: python sms twilio

-----------------------编辑-----------------------

我仍然不确定如何让request.form ['Body']正常工作。我可能没有正确使用此请求,但我不确定如何使用它。一个建议是成为一个听众,但我不知道从哪里开始。

所以我现在想:

1)我在哪里完全开玩笑? 2)关于如何建立听众的任何建议?

这是我设置的骨架:

from flask import Flask, request, redirect
import twilio.twiml
from twilio.rest import TwilioRestClient
from sys import exit

twil_number = "XXXXXXXXX"
sid = "XXXXXXXXXXXXXXXXXXXX"
token = "XXXXXXXXXXXXXXXXX"
tos = "XXXXXXXXXX"

client = TwilioRestClient(sid,token)


app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])

##### get the SMS ####

def smsGet():

    try:
        action = request.form['Body']
    except RuntimeError:
        action = raw_input("> ")

    return action.lower()


### Snd the SMS ####
def smsSend(bods):

    client.sms.messages.create(to=tos, from_=twil_number, body= bods)


class TestClass(object):

    def doStuff(self):

        smsSend("Intro Text")

        ## I don't know why this is buggering up. ###
        go = smsGet()

        if go == "yes":
            smsSend("yes")
            exit(1)

        else:
            pass
            exit(1)


a = TestClass()
a.doStuff()



#### running the app ###

if __name__ == "__main__":
    app.run(debug=True)

----------------------- older ----------------------- 我正在用twilio / python制作一个文本冒险游戏。没有数据库或任何东西,它只是一个基于python的文本冒险,我在shell本地运行。

所有发送短信的东西都很好,但我怎么得到这样的东西:

request.form['Body'].lower()

像这样工作:

raw_input("> ").lower()

到目前为止,我尝试过的大多数事情都让Flask抛出了这个错误:

RuntimeError('在请求上下文之外工作')

所以对于上下文。我的很多场景都设置如下:

class Hallway(Scene):
    def enter(self):

        hall = "You pause in the Hallway. You could: Go to the bedroom. Go to the kitchen to see if there's food. Check on your human in the office."
        send_sms(hall)

        #action = raw_input("> ").lower() 
        #would like this to work like raw _input()
        action = request.form['Body'].lower() 

        if action == "kitchen":
            return 'kitchen'
        elif action == "bedroom":
            return 'bedroom'
        elif action == "office":
            return 'office'
        else:
            nope = "But I don't want to hang in the hallway..."
            send_sms(nope)
            return 'hallway'

send_sms()就是这样:

def send_sms(bods):

    client.sms.messages.create(body=bods,to=tos,from_=froms)

有关我完全放弃的地方的任何建议吗?

谢谢! :)

2 个答案:

答案 0 :(得分:1)

所以,如果我理解你正在尝试做什么,你可能想要这样的东西(注意我没有运行它,所以它可能有一些小错误,但想法应该是合理的):< / p>

listener.py

from flask import Flask, request
from twilio.rest import TwilioRestClient
import twilio.twiml

import game

account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
twilio_client = TwilioRestClient(account_sid, auth_token)

app = Flask(__name__)

games = {}

@app.route("/", methods=['GET', 'POST'])
def accept_response():
    from_number = request.values.get('From')
    body = request.values.get('Body')

    try:
        games[from_number].queue.put(body)
    except KeyError:
        games[from_number] = game.Game(twilio_client, from_number, "your number goes here")
        games[from_number].start()

    return str(twilio.twiml.Response())

if __name__ == "__main__":
    app.run(debug=True)

game.py

import queue
from threading import Thread

class Game(Thread)

    def __init__(self, twilio, to_number, from_number):
        Thread.__init__(self, name=to_number)
        self.twilio = twilio
        self.from_number = from_number
        self.to_number = to_number
        self.queue = queue.Queue()

    def run(self):
        # Game logic goes here, e.g.:
        action = self.send_sms("You're being chased by a thing!", wait_for_response=True)        
        if action == "stop":
            self.send_sms("That was silly. The thing eats you, you die.")
        elif action == "run":
            self.send_sms("You're too slow! The thing eats you, you die.")
        else:
            self.send_sms("I don't know what you're trying to do, but the thing eats you, you die.")

    def send_sms(self, body, wait_for_response=False):
        self.twilio.messages.create(body=body, to=self.to_number, from_=self.from_number)
        if wait_for_response:
            response = self.queue.get()
            return response

因此,您运行侦听器,并且在Twilio端使用正确的配置它只是坐在那里并侦听SMS。当它收到一个时,它会检查游戏是否已经为用户运行。如果是这样,它将SMS的正文发送到游戏,以用作输入。否则,它将为该用户开启一款新游戏。

每个游戏实例都在它自己的线程中运行,你可以像raw_input那样使用Game实例的send_sms方法,也就是说,该游戏的用户将收到字符串参数作为SMS,并且他们的回复将是返回值。

我不知道你的游戏逻辑的其余部分是什么样的,但是要将它与你问题中的Scene类集成,你可能希望让Scene的consructor将游戏作为一个参数和将其分配给属性。那么,在enter()中,您可以编写类似action = this.game.send_sms('foo')

的内容

看来你可以使用threading.current_thread()(在这种情况下是Game实例)获取当前线程对象,因此不需要传递它。您可以从任何地方调用threading.current_thread().send_sms,也可以在场景的构造函数中将其连接起来。

答案 1 :(得分:0)

如果要从命令行中的Flask 内部运行该代码,则需要编写一个函数,该函数将从{{1}开始执行操作或使用request。它可能看起来像这样:

raw_input