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

Optimize Wxchat-bot doc #993

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

Optimize Wxchat-bot doc #993

wants to merge 4 commits into from

Conversation

Luffy2004-c
Copy link
Collaborator

@Luffy2004-c Luffy2004-c commented Oct 16, 2024

Summary by CodeRabbit

  • New Features

    • Added a new navigation item for "Build Wechat-bot with itchat" in the documentation.
    • Introduced a comprehensive guide for building a WeChat chatbot using the Pne framework and ItChat library.
    • Created a README.md file for the WeChat chatbot project detailing prerequisites and usage instructions.
  • Chores

    • Updated the requirements.txt file to include new dependencies: pne and promotulate.

Copy link

vercel bot commented Oct 16, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
promptulate ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 16, 2024 3:26pm

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes in this pull request involve the addition of a new navigation item in the VitePress configuration for documentation, specifically under the "Use Cases" section. A new file, wx-chatbot.md, has been created to provide a detailed guide on building a WeChat chatbot using the ItChat library and Pne framework. Additionally, a new README file for the WeChat chatbot project has been added, along with updates to the requirements.txt file to include new dependencies.

Changes

File Change Summary
docs/.vitepress/config.mts Added navigation item: { text: 'Build Wechat-bot with itchat', link: '/use_cases/wx-chatbot' }
docs/use_cases/wx-chatbot.md New file created providing a comprehensive guide for building a WeChat chatbot using ItChat and Pne.
example/wx-chatbot/README.md New README file added for the WeChat chatbot project, outlining purpose, prerequisites, and usage.
example/wx-chatbot/requirements.txt Added new dependencies: pne and promotulate.

Possibly related PRs

  • Add Wx chatbot doc #970: The changes in this PR include the addition of the wx-chatbot.md documentation file, which is directly related to the new navigation item added in the main PR's VitePress configuration.

Suggested reviewers

  • Undertone0809

Poem

In the garden of code, a new path we weave,
A WeChat bot blooms, oh, what a reprieve! 🌼
With ItChat and Pne, our dreams take flight,
A guide for all, shining so bright!
Hop on this journey, let’s code and create,
Together we’ll build, it’s never too late! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (11)
example/wx-chatbot/requirements.txt (1)

1-3: Add a newline at the end of the file

The file is missing a newline at the end, which is considered good practice and can prevent issues with some tools.

Add a newline at the end of the file:

itchat-uos == 1.4.1
pne
promotulate
+
example/wx-chatbot/README.md (5)

3-5: Enhance the introduction with brief explanations of pne and itchat.

The introduction is concise and clear about the project's purpose. However, it could be more informative by briefly explaining what pne and itchat are. This would help readers unfamiliar with these libraries.

Consider expanding the introduction like this:

## Introduction

This is a simple example of building a WeChat chatbot using pne (a framework for building AI applications) and itchat (a library for WeChat API). This combination allows for the creation of an AI-powered chatbot that can interact with users through WeChat.

7-17: Clarify WeChat permissions and mention OpenAI usage in the introduction.

The prerequisites section is well-structured, but there are two points that could use clarification:

  1. The "necessary permissions" for the WeChat account are not specified. It would be helpful to elaborate on what these permissions are or provide a link to documentation explaining them.

  2. The OpenAI API key requirement implies the use of OpenAI's services, which wasn't mentioned in the introduction. Consider adding this information to the introduction for better context.

Consider updating the prerequisites like this:

4. A WeChat account with the necessary permissions to use itchat (specify permissions or link to documentation)

Also, update the introduction to mention the use of OpenAI's services.


19-25: Enhance installation instructions with virtual environment setup and file location details.

The installation instructions are straightforward, but they could be improved by:

  1. Recommending the use of a virtual environment.
  2. Specifying the location of the requirements.txt file.

Consider updating the installation section like this:

## Installation

1. It's recommended to create and activate a virtual environment:

   ```bash
   python -m venv venv
   source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
  1. Install the necessary Python packages using pip:

    pip install -r requirements.txt

    Note: Ensure you're in the directory containing the requirements.txt file when running this command.


---

`27-34`: **Expand usage instructions with more details and expected behavior.**

The usage instructions provide basic information but could be more comprehensive. Consider the following improvements:

1. Provide more details on how to edit the `model_config` in `app.py`.
2. Explain what users should expect to see after running the command.
3. Include instructions on how to interact with the chatbot once it's running.


Here's a suggested expansion of the Usage section:

```markdown
## Usage

1. Edit the `model_config` in `app.py` to set your OpenAI API key:

   ```python
   model_config = {
       "model": "gpt-3.5-turbo",
       "api_key": "your-api-key-here"
   }
  1. Run the chatbot using the following command:

    python app.py
  2. After running the command, you should see output indicating that the bot is starting up. You may be prompted to scan a QR code with your WeChat app to log in.

  3. Once the bot is running, you can interact with it by sending messages to your WeChat account. The bot will respond based on the configured prompts and the OpenAI model's responses.

  4. To stop the bot, press Ctrl+C in the terminal where it's running.


---

`1-34`: **Consider adding additional sections to enhance the README**

The README provides essential information for setting up and running the WeChat chatbot. To make it more comprehensive and user-friendly, consider adding the following sections:

1. **License**: Specify the license under which this project is released.
2. **Contributing**: If you're open to contributions, provide guidelines on how others can contribute to the project.
3. **Troubleshooting**: Include common issues users might encounter and their solutions.
4. **Acknowledgements**: If applicable, acknowledge any third-party libraries or resources used in the project.


Here's a suggested structure for these additional sections:

```markdown
## Troubleshooting

If you encounter any issues, please check the following:

1. Ensure your OpenAI API key is correctly set in the `model_config`.
2. Check that your WeChat account has the necessary permissions for using itchat.
3. ...

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the [MIT License](LICENSE).

## Acknowledgements

- [pne](https://github.com/pne-ai/pne) - Framework for building AI applications
- [itchat](https://github.com/littlecodersh/ItChat) - WeChat API for Python
docs/.vitepress/config.mts (1)

73-74: Approve with minor suggestions for improvement

The addition of the new navigation item for the WeChat chatbot guide is correct and consistent with the existing structure. However, I have a few minor suggestions to enhance it:

  1. Correct the capitalization of "WeChat" in the text.
  2. Consider capitalizing "ItChat" for better readability.
  3. You might want to consider alphabetical ordering of use cases for easier navigation.

Here's a suggested revision:

-          { text: 'Build Wechat-bot with itchat', link: '/use_cases/wx-chatbot' },
+          { text: 'Build WeChat-bot with ItChat', link: '/use_cases/wx-chatbot' },
docs/use_cases/wx-chatbot.md (4)

5-21: Improve formatting and clarity in the prerequisites section.

The prerequisites section is informative, but its readability can be enhanced:

  1. Use consistent formatting for the list of prerequisites. Consider using Markdown bullet points (-) for all items.
  2. Clarify the installation instructions. The requirements.txt file is mentioned without prior context. Consider adding a note about its location or content.

Here's a suggested revision for the prerequisites list:

#### Prerequisites

Before starting, ensure you have the following:

- Python 3.x installed
- Basic understanding of Python
- A WeChat account
- The following Python packages:
  - itchat
  - pne
  - promptulate

You can install the necessary packages by running:

```bash
pip install -r requirements.txt

Note: Ensure that the requirements.txt file is in your project directory and contains the necessary package names.


<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Markdownlint</summary><blockquote>

5-5: Expected: h2; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)

</blockquote></details>

</details>

---

`23-35`: **Provide more information about the custom `chat_message` module.**

The import section is clear and well-structured. However, it includes a custom module `chat_message` that may not be familiar to readers.


Consider adding a brief explanation of the `chat_message` module's purpose and functionality. For example:

```markdown
- `chat_message`: A custom module for handling chat messages. This module likely contains classes or functions for processing and formatting WeChat messages.

This additional information will help readers understand the role of this custom module in the chatbot implementation.


159-179: Provide more context for the hotReload parameter in the startup() function.

The startup() function is well-implemented with proper error handling. However, the hotReload parameter in the itchat.auto_login() call could benefit from more explanation.

Consider adding a brief explanation of the hotReload parameter and its implications. For example:

def startup():
    try:
        itchat.auto_login(
            enableCmdQR=2,
            hotReload=False,   # Set to True to avoid logging in every time
            qrCallback=qrCallback
        )
        # ... rest of the function ...

You could also add a note in the explanatory text:

Note: The `hotReload` parameter is set to `False` in this example. Setting it to `True` allows the bot to reuse the previous login session, avoiding the need to scan the QR code every time the script is run. However, this may have security implications, so use it cautiously.

This additional information will help users understand the purpose and implications of the hotReload parameter.


207-228: Enhance the running instructions for better user guidance.

The main loop and running instructions are clear and concise. However, providing more detailed steps could help users, especially beginners, to run the chatbot more effectively.

Consider expanding the running instructions with the following details:

### Running the Chatbot

To run the bot:

1. Ensure all the code snippets from this tutorial are combined into a single Python file (e.g., `wx_chatbot.py`).
2. Set your OpenAI API key as an environment variable:
   ```bash
   export OPENAI_API_KEY='your-api-key-here'
  1. Run the script in your terminal:
    python wx_chatbot.py
  2. A QR code will be generated. Scan it with your WeChat app to log in.
  3. Once logged in, your bot will start receiving and responding to messages!

Note: Keep the terminal window open to keep the bot running. To stop the bot, press Ctrl+C in the terminal.


These detailed instructions will help users set up and run the chatbot more easily, reducing potential confusion or errors.

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**

<details>
<summary>📥 Commits</summary>

Files that changed from the base of the PR and between d07b3392c45dbe251322e1a59051b0fa5c162c7d and 1f6ad5706191ed4ef517be9cd1d646bd846b4216.

</details>

<details>
<summary>📒 Files selected for processing (4)</summary>

* docs/.vitepress/config.mts (1 hunks)
* docs/use_cases/wx-chatbot.md (1 hunks)
* example/wx-chatbot/README.md (1 hunks)
* example/wx-chatbot/requirements.txt (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>



<details>
<summary>🪛 LanguageTool</summary><blockquote>

<details>
<summary>docs/use_cases/wx-chatbot.md</summary><blockquote>

[grammar] ~126-~126: This phrase is duplicated. You should probably use “return None” only once.
Context: ...} skipped: {}".format(msg["MsgId"], e)) return None return None  This function:      •	Logs the message...

(PHRASE_REPETITION)

</blockquote></details>

</blockquote></details>
<details>
<summary>🪛 Markdownlint</summary><blockquote>

<details>
<summary>docs/use_cases/wx-chatbot.md</summary><blockquote>

5-5: Expected: h2; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)

---

92-92: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

93-93: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

94-94: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

95-95: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

96-96: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

97-97: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

98-98: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

132-132: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

133-133: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

134-134: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

142-142: null
Bare URL used

(MD034, no-bare-urls)

---

92-92: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

---

132-132: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

---

144-144: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

</blockquote></details>

</blockquote></details>

</details>

<details>
<summary>🔇 Additional comments (2)</summary><blockquote>

<details>
<summary>example/wx-chatbot/requirements.txt (1)</summary><blockquote>

`3-3`: **Clarify the purpose of the 'promotulate' dependency**

The purpose of the 'promotulate' dependency is not immediately clear from the context of a WeChat chatbot. 


Could you provide more information about how 'promotulate' is used in this project? If it's not directly related to the WeChat chatbot functionality, consider if it's necessary for this specific example.

To help verify the usage of 'promotulate', you can run the following script:



This will help us understand how 'promotulate' is being used in the project.

</blockquote></details>
<details>
<summary>docs/use_cases/wx-chatbot.md (1)</summary><blockquote>

`1-228`: **Overall, a well-structured and informative tutorial with room for improvements.**

This tutorial provides a comprehensive guide for building a WeChat chatbot using Pne and ItChat. It covers all the necessary steps from setup to implementation and running the bot. The explanations are clear, and the code snippets are generally well-written.

However, there are several areas where the tutorial could be improved:

1. Enhance the formatting and clarity of the prerequisites section.
2. Provide more context for custom modules and objects used in the code.
3. Improve code maintainability by using configuration for hardcoded values.
4. Address security concerns, particularly regarding the API key usage.
5. Optimize class implementations and error handling.
6. Provide more detailed running instructions for better user guidance.

Addressing these points will significantly enhance the quality and usefulness of this tutorial, making it more accessible to beginners and more valuable to experienced developers.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary><blockquote>

[grammar] ~126-~126: This phrase is duplicated. You should probably use “return None” only once.
Context: ...} skipped: {}".format(msg["MsgId"], e)) return None return None  This function:      •	Logs the message...

(PHRASE_REPETITION)

</blockquote></details>
<details>
<summary>🪛 Markdownlint</summary><blockquote>

5-5: Expected: h2; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)

---

92-92: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

93-93: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

94-94: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

95-95: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

96-96: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

97-97: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

98-98: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

132-132: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

133-133: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

134-134: Column: 6
Hard tabs

(MD010, no-hard-tabs)

---

142-142: null
Bare URL used

(MD034, no-bare-urls)

---

92-92: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

---

132-132: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

---

144-144: Expected: fenced; Actual: indented
Code block style

(MD046, code-block-style)

</blockquote></details>

</details>

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +2 to +3
promotulate
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Specify versions for new dependencies

It's a good practice to specify versions for all dependencies to ensure reproducibility and avoid potential compatibility issues in the future.

Consider updating the new dependencies with specific versions:

itchat-uos == 1.4.1
-pne
-promotulate
+pne == x.y.z
+promotulate == a.b.c

Replace x.y.z and a.b.c with the appropriate version numbers you're currently using or testing with.

Committable suggestion was skipped due to low confidence.

Comment on lines +37 to +51
### Step 2: Define the Message Handler

We use itchat.msg_register to define how the bot will respond to text messages. This method registers the message handler for incoming messages:

```python
@itchat.msg_register([TEXT])
def handler_single_msg(msg: Message):
try:
print("Get a new message: {}".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
```
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Refine the message handler function and provide context for the handler object.

The message handler section is informative, but there are a couple of points that could be improved:

  1. There's a duplicate return None statement at the end of the function. This is unnecessary and might confuse readers.
  2. The handler object is used in the function, but it's not defined or explained in this section.

To address these points:

  1. Remove the duplicate return None statement:
@itchat.msg_register([TEXT])
def handler_single_msg(msg: Message):
    try:
        print("Get a new message: {}".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
  1. Add a note explaining that the handler object will be defined later in the tutorial:
Note: The `handler` object used in this function will be defined later in the "Define the AI Response Logic" section.

These changes will improve the clarity and correctness of the code example.

Comment on lines +59 to +80
### Step 3: Generate a QR Code for WeChat Login

WeChat login requires scanning a QR code. Here, we provide several QR code generation options:

```python
def qrCallback(uuid, status, qrcode):
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=400x400&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 scan the QRCode on one of these websites:")
print(qr_api3)
print(qr_api4)
print(qr_api2)
print(qr_api1)
```
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance the QR code generation function for better maintainability and error handling.

The QR code generation function is functional, but it can be improved in terms of maintainability and robustness:

  1. The function currently uses hardcoded URLs for QR code generation services. This might make it difficult to update or maintain in the future.
  2. The function doesn't handle cases where the status is not "0".

Consider the following improvements:

  1. Use a configuration dictionary or list for the QR code service URLs:
QR_SERVICES = [
    "https://api.pwmqr.com/qrcode/create/?url={}",
    "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}",
    "https://api.qrserver.com/v1/create-qr-code/?size=400x400&data={}",
    "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}"
]

def qrCallback(uuid, status, qrcode):
    if status == "0":
        url = f"https://login.weixin.qq.com/l/{uuid}"
        print("You can scan the QRCode on one of these websites:")
        for service_url in QR_SERVICES:
            print(service_url.format(url))
    else:
        print(f"QR code generation failed with status: {status}")

This approach makes it easier to add, remove, or modify QR code services in the future.

  1. Add error handling for cases where the status is not "0".

These changes will make the function more maintainable and robust.

Comment on lines +181 to +203
### Step 5: Define the AI Response Logic

Here’s where we leverage Pne to generate AI-driven responses using the GPT-3.5 model. When a message is received, Pne processes it and returns a response that is sent back to the user.

```python
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", # Replace with your API key
"base_url": "https://api.openai.com/v1",
},
)
itchat.send(response.result, toUserName=receiver)

handler = MessageHandler()
```
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve security and optimize the MessageHandler class.

The AI response logic is well-explained, but there are a couple of issues that need to be addressed:

  1. The API key is hardcoded in the handle method, which is a significant security risk.
  2. The __init__ method of the MessageHandler class is empty and might be unnecessary.

To address these issues:

  1. Remove the hardcoded API key and use environment variables instead:
import os

class MessageHandler:
    def __init__(self):
        self.api_key = os.environ.get('OPENAI_API_KEY')
        if not self.api_key:
            raise ValueError("OPENAI_API_KEY environment variable is not set")

    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": self.api_key,
                "base_url": "https://api.openai.com/v1",
            },
        )
        itchat.send(response.result, toUserName=receiver)

handler = MessageHandler()
  1. Add a note in the tutorial about setting the environment variable:
Note: Before running the script, make sure to set your OpenAI API key as an environment variable:

```bash
export OPENAI_API_KEY='your-api-key-here'

Never include API keys directly in your code, especially if you plan to share or publish it.


These changes will significantly improve the security of the chatbot implementation and provide a better structure for the `MessageHandler` class.

<!-- This is an auto-generated comment by CodeRabbit -->

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant