我正在尝试制作一个Python脚本,该脚本使用fbchat
听Facebook聊天并搜索单词'cf'
。如果在聊天中检测到该单词,我想发送一个预定义的消息Answer1
。参见下面的代码和错误信息:
from fbchat import log, Client
from fbchat.models import *
wordImLookingFor = ['cf']
Answer1 =['Hello! how can i help you']
# Subclass fbchat.Client and override required methods
class EchoBot(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
# If you're not the author, echo
if author_id != self.uid:
if word in message_object:
print("The word is in the list!")
self.send(Message(text=answer1), thread_id=thread_id, thread_type=ThreadType.USER)
else:
print("The word is not in the list!")
client = EchoBot('user', 'pass')
client.listen()
解析异常... 追溯(最近一次通话): ... onMessage中的文件“ C:/Users/John/Downloads/fbd2.py”,第22行 如果message_object中的单词: TypeError:“消息”类型的参数不可迭代
答案 0 :(得分:2)
这是fbchat.models.Message的API
我相信您正在寻找文本字段
if word in message_object.text:
print("The word is in the list!")
编辑:
简单解决方案
对于下一个错误,in
关键字应使用单个字符串而不是字符串列表。由于您要在邮件中查找几个关键字,因此请对列表中的每个单词执行该case语句。
if author_id != self.uid:
for word in wordImLookingFor:
if word in message_object.text:
print("The word is in the list!")
self.send(Message(text=answer1), thread_id=thread_id, thread_type=ThreadType.USER)
else:
print("The word is not in the list!")
扩展解决方案
由于您最终将要搜索一组多个关键字,并且大概每个关键字都应引起一个不同的Answer,因此您可以通过创建一个关键字字典:answer来节省一些复杂性。
keywords = {'cf': 'Hello! how can i help you', 'key2': 'Answer2'}
class EchoBot(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))
if author_id != self.uid:
for word in message_object.text.split():
try:
self.send(Message(text=keywords[word]), thread_id=thread_id, thread_type=ThreadType.USER)
print(word + "is in the list!")
except KeyError:
print(word + "is not in the list!")
答案 1 :(得分:1)
您的例外情况是self.send(Message(text = answer1)
您似乎正在尝试以LIST而不是字符串的形式发送文本。
消息无法遍历列表,但需要一个简单的字符串。
Answer1 =['Hello! how can i help you']
Answer1 = 'Hello! How can I help you?'