Pregunta

I built a quiz game in Python that works with the Twilio API so I can run the game through sms to my Twilio number. I'm trying to figure out how to pass a response that will show standard text and an emoji when its received by the sending phone.

I've been working on understanding unicode vs. ascii character set and encoding and decoding in utf-8. Where I last landed is the following code which just prints out the unicode code point like a regular string on the mobile phone. The gap appears to be how to isolate and pass a code point that the phone can interpret. Any ideas or pointers on how to do this? Or is there a different approach someone would recommend?

The current state of the code is as follows:

# -*- coding: utf-8 -*-

from flask import render_template, flash, redirect, session, url_for, request, jsonify, g
from flask import Response
from app import app
from config import TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN
from twilio import twiml
from twilio.rest import TwilioRestClient
import re, random

client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)


def simplify_txt(submitted_txt):
    response_letters = re.sub(r'\W+', '', submitted_txt)
    return response_letters.lower()

@app.route("/quiz_game")
def quiz_game():

   response = twiml.Response()

    from_number = str(request.values.get('From', None))
    body = request.values.get('Body', None)
    simplify_body = simplify_txt(body)

    questions = { 
            0: "What word is shorter when you add two letters to it?",
            1: "If I drink, I die. If i eat, I am fine. What am I?",
            2: "What kind of tree is carried in your hand?",
            3: "Thanks for playing.",
            4: ""
    }

    # Stripped down answers to compare to text in case multiple word answer
    simplify_answers = { 
            1:"short", 
            2:"fire", 
            3:"palm",
            4:""
            }

    # Pretty print answers
    print_answers = { 
            1:"short", 
            2:"fire", 
            3:"palm",
            4:""
            }

    # if from_number not in track_user:
    if from_number not in session:
        session[from_number] = 0
        counter = session.get('counter', 0)
        counter += 1
        session['counter'] = counter
        message = "Shall we play a game? %s "  % questions[0]
    else:
        game_round = session['counter']

        if simplify_answers[game_round] == simplify_body:
            session[from_number] += 10
            score = session[from_number]

            message = "Correct Answer. You have %d points out of 30. %s" % (score, questions[game_round])

            message += unicode('u1f31f',"unicode_escape").encode('utf-8') 

        else:
            score = session[from_number]
            message = "Wrong answer. We were looking for %s. Your score is %d out of 30. %s" % (print_answers[game_round], score, questions[game_round])

        session['counter'] += 1


    if session['counter'] > 3:
        session.pop(from_number, None)
        session['counter'] = 0


    response.sms(message)

    return Response(str(response))

UPDATE: Part of the problem was applying the sms method to the message variable turned it into XML format which didn't preserve the unicode code point. Applying messages.create method captured and preserved the unicode code point so it could be interpreted by the mobile device.

For the fix, I applied Rob's recommendation primarily to the last two lines of the code by replacing response.sms and the return with the client.messages.create and passing in the message variable to the body parameter. I also applied the u for unicode to all strings assigned to the message variable as well as added emoji code points/images to the messages. These made texting emoji work. If you want to see the update, checkout: https://github.com/nyghtowl/Twilio_Quiz

¿Fue útil?

Solución

Great question on how to send emoji using the Twilio Python module. Also love the Wargames reference. Think I know what is happening here.

The unicode value for the glowing star symbol is U+1F31F which represented as a Python unicode literal is u"\U0001F31F". Without the plus sign, it is actually a different codepoint that is not the glowing star emoji.

So to send in this particular example, you would do something like:

from twilio.rest import TwilioRestClient

# Set Twilio credentials
TWILIO_ACCOUNT_SID = "ACxxxxxxxxxxxxx"
TWILIO_AUTH_TOKEN = "yyyyyyyyyyyyyyyy"
TWILIO_NUMBER = "+15558675309"

# Instantiate Twilio REST client
client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

# Send a glowing star emoji
client.messages.create(from_=TWILIO_NUMBER, to="+15556667777", body=u"Here is your tasty emoji: \U0001F31F")

Hope that helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top