0

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

我仍然不确定如何让 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)

----------------------- 年长 ----------- 我是用 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)

关于我完全搞砸的地方有什么建议吗?

谢谢!:)

4

2 回答 2

1

所以,如果我理解你想要正确地做的事情,你可能想要这样的东西(注意我没有运行这个,所以它可能有一些小错误,但这个想法应该是合理的):

监听器.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)

游戏.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 的正文发送到游戏,用作输入。否则,它会为该用户启动一个新游戏。

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

我不知道您的游戏逻辑的其余部分是什么样的,但是要将其与问题中的 Scene 类之类的东西集成,您可能希望让 Scene 的构造函数将 Game 作为参数并将其分配给属性。所以,那么,enter()你可以写一些类似的东西action = this.game.send_sms('foo')

看来您可以使用threading.current_thread()(在本例中为 Game 实例)获取当前线程对象,因此无需传递它。您可以threading.current_thread().send_sms从任何地方调用,也可以将其连接到场景的构造函数中。

于 2013-10-14T00:01:49.173 回答
0

如果您想从 Flask 内部从命令行运行该代码,您需要编写一个函数来获取操作,无论是从request或 using raw_input。它可能看起来像这样:

from flask import request

def get_action():
    try:
        action = request.form['Body']
    except RuntimeError:
        action = raw_input("> ")
    return action.lower()
于 2013-10-12T03:45:18.010 回答