👉 项目官网:https://www.python-office.com/ 👈

github star

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

今天教你怎么用 python-office 开发微信机器人——自动回复消息、管理群聊。

1、自动回复消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import office

# 设置自动回复
@office.robot.reply()
def auto_reply(msg):
if '你好' in msg:
return '你好!我是程序员晚枫的微信机器人~'
elif '课程' in msg:
return '想了解课程可以加微信:aiwf365'
else:
return '收到,稍后回复你!'

# 启动机器人
office.robot.start()

运行后,有人给你发消息,会自动回复!

2、关键词自动回复

1
2
3
4
5
6
7
8
9
10
11
12
13
import office

# 设置关键词回复
office.robot.reply(
keywords={
'价格': '我们的课程限时优惠,扫码了解:xxx',
'地址': '我们在重庆,欢迎来玩~',
'课程': 'Python自动化办公课程,加微信 python-office 咨询',
'帮助': '发送关键词:价格/地址/课程'
}
)

office.robot.start()

3、群管理:自动踢人

1
2
3
4
5
6
7
8
9
10
import office

# 启动群管理机器人
office.robot.group(
auto_kick=True, # 自动踢人
keywords=['广告', '赌博', '色情'], # 关键词
notice='发广告将被自动移出群聊' # 入群公告
)

office.robot.start()

4、自动发消息

1
2
3
4
5
6
7
8
9
10
11
12
13
import office

# 给指定好友发消息
office.robot.send(
user='好友昵称',
msg='你好,这是自动发送的消息'
)

# 给群发消息
office.robot.send_group(
group='群名称',
msg='各位好,这是自动发送的通知'
)

5、实战案例:课程咨询机器人

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
import office

def course_robot(msg):
"""课程咨询机器人"""
msg_lower = msg.lower()

if '价格' in msg or '多少钱' in msg:
return '''课程价格:
- 零基础入门课:98元
- 进阶课:198元
- 套餐:268元(两门课)
回复"报名"获取购买方式'''

elif '报名' in msg:
return '报名请加微信:aiwf365,备注:报名'

elif '试听' in msg or '试看' in msg:
return '试听课在B站搜:程序员晚枫,免费观看~'

elif '时间' in msg or '多久' in msg:
return '课程是视频课,随时可学,永久有效'

else:
return '我是课程助手,回复关键词:价格/报名/试听/时间'

@office.robot.reply()
def handler(msg):
return course_robot(msg)

office.robot.start()

6、实战案例:定时群发消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import office
import time
from datetime import datetime

def daily_broadcast():
"""每日定时群发"""
friends = ['张三', '李四', '王五']
message = f'【早安】{datetime.now().strftime("%Y-%m-%d")} 早安!今天也要加油哦~'

for friend in friends:
office.robot.send(user=friend, msg=message)
time.sleep(1) # 避免被限制

print('群发完成!')

# 每天早上8点执行
# 可以配合Windows任务计划程序使用
daily_broadcast()

7、常见问题

Q:微信机器人会被封号吗?

A:官方不建议使用第三方工具,建议仅用于个人学习。

Q:消息发不出去?

A:检查是否开启了微信网页版权限,或者尝试重启微信。

Q:Mac能用吗?

A:部分功能需要Windows环境支持。

8、下讲预告

学会了微信机器人,下一讲我们学 AI编程入门——用AI辅助写代码。

敬请期待!


有问题欢迎加微信 python-office 进群交流~

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

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!