github star gitee star atomgit star PyPI Downloads AI编程 AI交流群

大家好,这里是程序员晚枫,正在all in AI编程实战

第25讲:AI微信机器人——让AI帮你聊微信

AI微信机器人能做什么?

  • 自动回复好友消息
  • 智能客服
  • 定时群发消息
  • 自动拉群

1、安装微信库

1
pip install python-office itchat-unofficial

2、自动回复好友

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import itchat
from openai import OpenAI

client = OpenAI(api_key="你的Key", base_url="https://api.deepseek.com")

@itchat.msg_register(itchat.content.TEXT)
def reply(msg):
"""收到消息时自动回复"""
user_message = msg["Text"]

# 过滤群消息,只处理好友
if msg["FromUserName"].startswith("@"):
# AI生成回复
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{
"role": "user",
"content": f"你是一个热情的客服,回复用户问题:\n{user_message}"
}]
)
reply_text = response.choices[0].message.content

# 发送回复
itchat.send(reply_text, msg["FromUserName"])
print(f"已回复:{reply_text}")

# 登录微信
itchat.auto_login(hotReload=True)
itchat.run()

3、关键词自动回复

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import itchat

keyword_responses = {
"价格": "我们产品的价格是XXX,详情请联系客服。",
"地址": "我们的地址是:重庆市渝北区XXX",
"营业时间": "我们的营业时间是:周一到周五 9:00-18:00",
}

@itchat.msg_register(itchat.content.TEXT)
def keyword_reply(msg):
for keyword, response in keyword_responses.items():
if keyword in msg["Text"]:
itchat.send(response, msg["FromUserName"])
return

itchat.auto_login(hotReload=True)
itchat.run()

4、定时群发消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import itchat
import schedule
import time

def send_broadcast():
"""向所有好友发送消息"""
friends = itchat.get_friends()

response = client.chat.completions.create(
model="deepseek-chat",
messages=[{
"role": "user",
"content": "生成一条温馨的早安问候语,不超过50字"
}]
)
message = response.choices[0].message.content

for friend in friends[:50]: # 避免被封,每次发50人
try:
itchat.send(message, friend["UserName"])
print(f"已发送给:{friend['NickName']}")
except:
pass
time.sleep(2) # 避免频率过高

# 每天早上8点群发
schedule.every().day.at("08:00").do(send_broadcast)

itchat.auto_login(hotReload=True)

while True:
schedule.run_pending()
time.sleep(60)

5、AI客服机器人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@itchat.msg_register(itchat.content.TEXT)
def ai客服(msg):
"""AI智能客服"""
user_message = msg["Text"]

# 构建上下文
system_prompt = """你是程序员晚枫的AI助手"小枫"。
性格:热情、专业、幽默
擅长:Python编程、AI使用、技术问题解答
回复风格:简洁有趣,带emoji"""

response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message}
]
)

reply_text = response.choices[0].message.content
itchat.send(reply_text, msg["FromUserName"])

itchat.auto_login(hotReload=True)
itchat.run()

6、注意事项

⚠️ 微信机器人有封号风险:

  • 不要频繁发送消息
  • 不要发送敏感内容
  • 建议使用小号测试

下讲预告

学会了AI微信机器人,下一讲我们学 AI应用上线部署——让你的AI应用跑起来。

敬请期待!


程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

前3讲可以试听,试听链接:https://www.bilibili.com/cheese/play/ss982042944