[好,所以我获得了WhatsApp和Twilio的批准(在Facebook商业验证之后),可以使用WhatsApp API向我的客户发送约会提醒。我配置了消息模板,它们也得到了批准。检查下面的图像:
我已经用Python编写了代码,在其中我从托管在云上的PostgreSQL服务器(使用psycopg2)中选择数据,然后将消息发送到使用查询获取的电话号码。这是代码:
from twilio.rest import Client
import psycopg2
import time
account_sid = 'AC54xxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'f1384yyyyyyyyyyyyyyyyyyyyyyyyyyy'
connection_string = ""
conn = psycopg2.connect(user = "xxxx",
password = "yyyyyy",
host = "zzzzzzzzzzzzzzz.zzzzzzzzzzzz",
port = "ABCD",
database = "some_db")
cur = conn.cursor()
cur.execute("""query to pick data""")
rows = cur.fetchall()
client_phone_list = []
phone_list_not_received = []
session_date_list = []
session_time_list = []
client_first_name_list = []
for row in rows:
session_date_list.append(row[0])
session_time_list.append(row[1])
client_first_name_list.append(row[2])
client_phone_list.append(row[3])
cur.close()
conn.close()
client = Client(account_sid, auth_token)
message_reminder_template = """Hello {},
This is a reminder about your session today at {}. Please be on time to utilize the full length of
the session and avoid distress :)
We look forward to taking care of you!"""
for i in range(len(client_phone_list)):
first_name = client_first_name_list[i]
appointment_time = session_time_list[i]
message_body = message_reminder_template.format(first_name, appointment_time)
print(message_body)
message = client.messages.create(body = str(message_body),
from_ = 'whatsapp:+1(mytwilionumber)',
to = 'whatsapp:+91'+client_phone_list[i])
time.sleep(10)
text_status = message.status
print(text_status)
[每当我运行此代码时,返回的消息状态始终为'已排队'。我已经检查过我不是在使用“测试凭据”,而是在使用“实时凭据”。
我还检查了error_code和error_message,它们返回为NULL。因此,没有错误,但是消息未发送。我该如何更改?
任何帮助将不胜感激。
还请注意,上面代码中使用的消息正文是approved作为WhatsApp的模板。
Twilio开发人员推广人员在这里。
在您发出API请求以发送消息时,状态将以“排队”的形式返回给代码。这就是您的代码中的这一点:
message = client.messages.create(body = str(message_body),
from_ = 'whatsapp:+1(mytwilionumber)',
to = 'whatsapp:+91'+client_phone_list[i])
尽管,您下一步将无法执行:
time.sleep(10)
text_status = message.status
print(text_status)
等待10秒钟,然后从创建消息时返回的消息对象读取状态仍将返回“已排队”。
如果您想在10秒钟后获取消息状态以查看其是否已发送,则需要再次拨打messages API,如下所示:
time.sleep(10)
latest_message = client.messages(message.sid).fetch()
print(latest_message.status)
有关跟踪消息状态的更有效方法,请查看此tutorial on receiving webhooks for message status updates。
让我知道是否有帮助。