Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add wx-chatbot Use Case #933

Merged
merged 2 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions example/wx-chatbot/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import time

import chat_message
import itchat
import pne
from itchat.content import TEXT
from itchat.storage.messagequeue import Message

from promptulate.utils import logger


@itchat.msg_register([TEXT])
def handler_single_msg(msg: Message):
try:
print(msg)
print("Get a new messsage: {}".format(msg.Content))
handler.handle(chat_message.ReceiveMessage(msg))
except NotImplementedError as e:
logger.debug("[WX]single message {} skipped: {}".format(msg["MsgId"], e))
return None
return None


def qrCallback(uuid, status, qrcode):
# logger.debug("qrCallback: {} {}".format(uuid,status))
if status == "0":
url = f"https://login.weixin.qq.com/l/{uuid}"

qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
qr_api2 = (
"https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(
url
)
)
qr_api3 = "https://api.pwmqr.com/qrcode/create/?url={}".format(url)
qr_api4 = "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(
url
)
print("You can also scan QRCode in any website below:")
print(qr_api3)
print(qr_api4)
print(qr_api2)
print(qr_api1)


def startup():
try:
# itchat.instance.receivingRetryCount = 600 # 修改断线超时时间
hotReload = False
itchat.auto_login(
enableCmdQR=2,
hotReload=hotReload,
qrCallback=qrCallback,
)
user_id = itchat.instance.storageClass.userName
name = itchat.instance.storageClass.nickName
logger.info(
"Wechat login success, user_id: {}, nickname: {}".format(user_id, name)
) # noqa: E501
itchat.run()
except Exception as e:
logger.exception(e)


class MessageHandler:
def __init__(self):
pass

def handle(self, msg: chat_message.ReceiveMessage):
receiver = msg.FromUserName
response = pne.chat(
messages=msg.Content,
model="gpt-3.5-turbo",
model_config={
"api_key": "sk-xxxxxx",
"base_url": "https://api.openai.com/v1",
},
)
itchat.send(response.result, toUserName=receiver)

Comment on lines +65 to +80
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider removing the empty __init__ method and moving the hardcoded API key to a configuration file or environment variable.

  • The empty __init__ method in the MessageHandler class is unnecessary and can be removed.
  • The hardcoded API key in the model_config dictionary should be moved to a configuration file or environment variable for security reasons.

Apply this diff to remove the empty __init__ method:

 class MessageHandler:
-    def __init__(self):
-        pass
-
     def handle(self, msg: chat_message.ReceiveMessage):
         receiver = msg.FromUserName
         response = pne.chat(

To move the API key to a configuration file or environment variable, you can use a library like python-dotenv to load the API key from a .env file or directly access it from an environment variable using os.getenv().

Committable suggestion was skipped due to low confidence.


handler = MessageHandler()


if __name__ == "__main__":
startup()
while True:
time.sleep(1)
51 changes: 51 additions & 0 deletions example/wx-chatbot/chat_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from itchat.storage.messagequeue import Message


class ChatMessage(object):
MsgId = None
FromUSerName = None

ToUserName = None
Content = None
MsgType = None
Status = None
ImgStatus = None
CreateTime = None
VoiceLength = None
PlayLength = None
FileName = None
FileSize = None
Url = None
from_user_id = None
from_user_nickname = None
to_user_id = None
to_user_nickname = None
other_user_id = None
other_user_nickname = None
my_msg = False
self_display_name = None

is_group = False
is_at = False
actual_user_id = None
actual_user_nickname = None
at_list = None

_prepare_fn = None
_prepared = False
_rawmsg = None


class ReceiveMessage(ChatMessage):
FromUserName = None

def __init__(self, msg: Message):
self.msg = msg
for key, value in self.msg.items():
setattr(self, key, value)

def __str__(self):
result = "[ReceiveMessage]"
for key, value in vars(self).items():
result += "{}: {}\n".format(key, value)
return result
1 change: 1 addition & 0 deletions example/wx-chatbot/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
itchat-uos == 1.4.1