跟随本文,你的微信号将带有计算器的 Buff。不多说,看图:

发送中文/英文问号加上表达式,就可以得到计算结果。运算符支持加减乘除和括号。
准备
- Python 3
- pip3 install itchat
- 一个微信号
主程序代码 – cal_wechat.py
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 34 35 36 37 38 39 |
#!/usr/bin/env python3 import itchat from itchat.content import * # 计算表达式的结果 def calculate(prompt: str): alfabeto = re.search('[a-zA-Z].*', prompt) # 禁止表达式中出现字母 # 这样可以限定 eval() 只能处理数学表达式 if alfabeto is None: reply = '' try: reply = "计算结果是:" + str(eval(prompt)) except SyntaxError: reply = '计算出错了,式子不对。' except NameError: reply = '不能计算结果,这不是个式子。' return reply else: return '不能计算结果,这不是个式子。' @itchat.msg_register(TEXT) def text_reply(msg): text = msg.text # 仅响应以问号开头的文本 if text.startswith('?') or text.startswith('?'): # 删除末尾的等号,如有的话 if text.endswith('='): text = text[:-1] # 删除开始的问号,删除空白字符,进行计算 reply = calculate(text[1:].strip().replace(' ', '')) return reply if __name__ == '__main__': # enableCmdQR=2 用于在命令行显示二维码 # hotReload=True 用于在一段时间内记住登入信息 itchat.auto_login(hotReload=True, enableCmdQR=2) itchat.run() |
保存并运行。程序会显示微信网页端的登入二维码,扫描登入就 OK 了。
相关资料
itchat 是一个开源的 Python 微信库。官方文档:https://itchat.readthedocs.io/zh/latest/
用eval会有安全问题吗?
代码里已经限制了
eval()
,只能传入符号和数字。不接受包含字母的参数。这么一来,就只能执行基本的数学表达式了。