Of course. Here is a comprehensive guide for using itchat with Python 2.7.

⚠️ Important: Python 2.7 is End-of-Life (EOL)
First and foremost, it's crucial to understand that Python 2.7 reached its official end-of-life on January 1, 2025. This means:
- No Security Updates: You are exposed to potential security vulnerabilities.
- No Bug Fixes: Issues you encounter will not be fixed by the core Python team.
- No New Features: You cannot use any modern Python libraries or syntax.
- Library Incompatibility: Most new libraries, including the latest versions of
itchat, do not support Python 2.7.
Strong Recommendation: You should migrate your projects to Python 3 as soon as possible. It is the future of the language, and it will save you from many headaches in the long run.
However, if you absolutely must use itchat with Python 2.7 for a legacy project, here is how you can do it.
Step 1: Install itchat for Python 2.7
You can install itchat using pip. The last version of itchat that officially supported Python 2.7 was itchat==1.3.10. It's best to specify this version to ensure compatibility.
Open your terminal or command prompt and run:
pip install itchat==1.3.10
If you have both Python 2 and Python 3 installed, you might need to use pip2:
pip2 install itchat==1.3.10
Step 2: Basic Usage Example
The API for itchat in Python 2.7 is almost identical to its earlier Python 3 versions. Here is a simple "Hello, World!" example that logs in and sends a message.
# -*- coding: utf-8 -*-
# This line is essential for Python 2 to handle Chinese characters correctly
import itchat
# Login to WeChat
# The hotReload=True parameter will save a login status file,
# so you don't have to scan the QR code every time you run the script.
# It will automatically re-login if the session expires.
itchat.auto_login(hotReload=True)
# Get your own username (your unique WeChat ID)
my_username = itchat.get_friends()[0]['UserName']
print("My username is: " + my_username)
# Send a message to a file helper (a special chat for automation)
# This is a safe way to test without sending to a real contact.
itchat.send('Hello from my Python 2.7 bot!', toFileHelper=True)
# You can also send to a specific contact by their nickname
# First, find the friend's UserName
# friends = itchat.search_friends(nickName='Friend\'s Nickname')
# if friends:
# friend_username = friends[0]['UserName']
# itchat.send('This message is for you!', toUserName=friend_username)
# else:
# print("Friend not found.")
# Logout (optional, but good practice)
itchat.logout()
Step 3: Handling Chinese Characters (Crucial for Python 2)
Python 2 handles Unicode strings differently from Python 3. This is the most common source of errors when working with itchat, as WeChat chat messages are often in Chinese.
You must add the line # -*- coding: utf-8 -*- at the very top of your Python file. This tells the Python interpreter to read the file using UTF-8 encoding.
Additionally, when dealing with strings from WeChat, you should ensure they are Unicode strings. The itchat library generally handles this, but if you encounter issues, you can explicitly decode:
# Example of handling a message
import itchat
itchat.auto_login(hotReload=True)
@itchat.msg_register(itchat.content.TEXT)
def handle_text_message(msg):
# msg['Text'] should already be a unicode string in Python 2.7 with itchat
# but if you have issues, you can force it:
# text = msg['Text'].decode('utf-8')
sender_nickname = msg['FromUserName']['NickName'] # This is already unicode
received_text = msg['Text']
print(u"Received from {}: {}".format(sender_nickname, received_text))
# Echo the message back
itchat.send(u"Echo: " + received_text, msg['FromUserName'])
itchat.run()
Step 4: Common Use Cases
Here are examples for common tasks, all compatible with Python 2.7.
A. Get a List of Friends
import itchat
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)[1:] # [0] is yourself
print("You have {} friends.".format(len(friends)))
for i, friend in enumerate(friends):
print(u"{}. {}: {}".format(i+1, friend['NickName'], friend['UserName']))
B. Send a Message to All Friends
Warning: Be very careful with this. Do not spam your contacts. This is for demonstration purposes only.
import itchat
import time
itchat.auto_login(hotReload=True)
# Get your own info (the first element in the friends list)
myself = itchat.get_friends()[0]
# Get all friends except yourself
friends = itchat.get_friends()[1:]
# The message you want to send
message = u"Hello from my Python 2.7 bot! This is a test message."
print("Sending message to {} friends...".format(len(friends)))
for friend in friends:
# It's good practice to add a delay to avoid being blocked by WeChat
try:
itchat.send(message, toUserName=friend['UserName'])
print(u"Sent to: {}".format(friend['NickName']))
time.sleep(2) # Wait for 2 seconds between messages
except Exception as e:
print(u"Failed to send to {}: {}".format(friend['NickName'], e))
print("Finished sending messages.")
itchat.logout()
Troubleshooting Common Issues
SyntaxError: Non-ASCII character: This means you forgot to add# -*- coding: utf-8 -*-at the top of your file.UnicodeEncodeErrororUnicodeDecodeError: This is a classic Python 2 Unicode issue. Ensure your file is saved with UTF-8 encoding and that you are handling strings correctly (as shown in Step 3).itchat.exceptions.LoginException: This usually means your login session has expired or theitchat.pklfile is corrupted. Delete theitchat.pklfile and run the script again to force a new QR code scan.- Message Sending Fails: This could be due to rate-limiting by WeChat. Add a
time.sleep()delay between sending messages to real contacts. Also, ensure you are using the correcttoUserName(theUserNamefield from the friend's info, not theirNickName).
Final Recommendation
While the information above will help you get itchat running on Python 2.7, the most sustainable and secure path forward is to migrate to Python 3. The code for itchat in Python 3 is largely the same, and you will benefit from a modern, supported language ecosystem.
