Lambda函数报错“Object of type function is not JSON serializable”求助
问题排查:Tweepy机器人部署在AWS Lambda中非问候回复分支报错“Object of type function is not JSON serializable”
问题描述
将Tweepy机器人部署在AWS Lambda中,其他功能均正常运行,仅非问候场景的回复分支触发报错:Object of type function is not JSON serializable。以下是机器人完整代码及错误栈信息:
完整代码
import tweepy import random import os import json import boto3 read = tweepy.Client(os.getenv('btok')) write = tweepy.Client( consumer_key=os.getenv('ckey'), consumer_secret=os.getenv('csec'), access_token=os.getenv('atok'), access_token_secret=os.getenv('atos') ) # 声明变量 user_id = 1568306756798775297 greet = random.choice(list(open('greetings.txt'))) # 从列表中随机选择问候语 reply = random.choice(list(open('replies.txt'))) # 从列表中随机选择回复语 strings = {'hi', 'hello', 'hey', 'hai'} # 识别的问候关键词 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('lastid') def main(event, context): # TODO implement reply() return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } def reply(): value = table.get_item(Key={'lastidkey': '1'}) last = value['Item']['lidval'] response = read.get_users_mentions(user_id, since_id=last) # 获取新提及 for tweet in response.data: text = tweet.text id = tweet.id if any(x in text.lower() for x in strings): write.create_tweet(in_reply_to_tweet_id=id, text=greet) # 问候场景回复问候语 else: write.create_tweet(in_reply_to_tweet_id=id, text=reply) # 非问候场景回复随机内容 table.put_item(Item={'lastidkey': '1', 'lidval': str(tweet.id)}) # 将最新ID写入DynamoDB
错误栈信息
{ "errorMessage": "Object of type function is not JSON serializable", "errorType": "TypeError", "requestId": "cb6423eb-e27e-4229-b322-c6df9fad3b5c", "stackTrace": [ " File \"/var/task/reply.py\", line 25, in main\n reply()\n", " File \"/var/task/reply.py\", line 41, in reply\n write.create_tweet(in_reply_to_tweet_id=id, text=reply) # otherwise, it's a random reply\n", " File \"/opt/python/tweepy/client.py\", line 824, in create_tweet\n return self._make_request(\n", " File \"/opt/python/tweepy/client.py\", line 126, in _make_request\n response = self.request(method, route, params=request_params,\n", " File \"/opt/python/tweepy/client.py\", line 83, in request\n with self.session.request(\n", " File \"/opt/python/requests/sessions.py\", line 573, in request\n prep = self.prepare_request(req)\n", " File \"/opt/python/requests/sessions.py\", line 484, in prepare_request\n p.prepare(\n", " File \"/opt/python/requests/models.py\", line 371, in prepare\n self.prepare_body(data, files, json)\n", " File \"/opt/python/requests/models.py\", line 511, in prepare_body\n body = complexjson.dumps(json, allow_nan=False)\n", " File \"/var/runtime/simplejson/__init__.py\", line 398, in dumps\n return cls(\n", " File \"/var/runtime/simplejson/encoder.py\", line 296, in encode\n chunks = self.iterencode(o, _one_shot=True)\n", " File \"/var/runtime/simplejson/encoder.py\", line 378, in iterencode\n return _iterencode(o, 0)\n", " File \"/var/runtime/simplejson/encoder.py\", line 272, in default\n raise TypeError('Object of type %s is not JSON serializable' %\n" ] }
问题原因与修复方案
核心问题
变量名与函数名冲突:你先定义了存储随机回复文本的变量reply,随后又定义了同名的reply()函数。当代码执行到非问候分支的write.create_tweet(..., text=reply)时,reply已经被后面的函数覆盖,实际传入的是函数对象而非预期的文本字符串,导致Tweepy尝试将函数序列化为JSON时失败。
修复步骤
- 重命名回复文本变量:将存储随机回复的变量名改为
reply_text(或其他不与函数冲突的名称)。 - 更新代码中引用该变量的位置:在非问候分支中使用新的变量名。
修改后的关键代码片段:
# 变量声明部分 greet = random.choice([line.strip() for line in open('greetings.txt')]) # 读取时去除换行符 reply_text = random.choice([line.strip() for line in open('replies.txt')]) # 重命名变量并去除换行符 # 非问候回复分支 else: write.create_tweet(in_reply_to_tweet_id=id, text=reply_text) # 使用新变量名
额外优化建议
- 读取文件时添加
strip()方法,去除每行末尾的换行符,避免回复内容带有多余的空白行。 - 避免在Python中使用相同名称命名变量和函数,这类命名冲突容易引发难以排查的逻辑错误。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

