“C:\Users\ngass\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py”, line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File “C:\Users\ngass\Downloads\Telegram-Autoforwarder-master\Telegram-Autoforwarder-master\TelegramForwarder.py”, line 111, in main
await forwarder.list_chats()
File “C:\Users\ngass\Downloads\Telegram-Autoforwarder-master\Telegram-Autoforwarder-master\TelegramForwarder.py”, line 26, in list_chats
chats_file.write(f"Chat ID: {dialog.id}, Title: {dialog.title} \n")
File “C:\Users\ngass\AppData\Local\Programs\Python\Python312\Lib\encodings\cp1252.py”, line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeEncodeError: ‘charmap’ codec can’t encode character ‘\U0001f43a’ in position 55: character maps to
It’s trying to encode the character '\U0001f43a'
('\N{WOLF FACE}'
) to cp1252
, but that encoding doesn’t support that character.
Presumably, cp1252
is the default encoding. What you really need is UTF-8
.
If you’re using a downloaded Python package, see whether there’s a way to specify the encoding to use.
Please how can i change it I am new to python.
Hello Matthew,
thanks for you for the response.
could you please guide me how to solve this issue.
I am really new to this.
Thanks
Hi,
the '\U0001F43a'
is a 32-bit Unicode escapes special character.
What do you want to encode it to per the error:
Hello Paul,
thank you the input here is what I am trying to encode
python telegramForwarder.py
Please let me know how to modify. I am really new with python.
Thanks
William
Hi,
I don’t know what telegramForwarder.py
is. That to me is a black box since I am not privy to the code inside and neither am I familiar with the module. However, if you want to send this info as ‘standard’ UTF-8
, try encoding it first to utf-8
.
The following screenshot shows how I start out with the original Unicode UTF-32 special character.
I then encode it and assign it to a variable. Try passing the new encoded variable. At the other end, they can decode it and end up with the original message (special character).
Thanks Paul,
but I really don’t nothing about python.
should encode from this screenshot
if Yes can I have the details?
This is what chatgpt gave me. I tried isn’t working
Assume dialog.id and dialog.title are defined elsewhere in your code
chat_info = f"Chat ID: {dialog.id}, Title: {dialog.title} \n"
Encode the chat_info string as UTF-8
utf8_chat_info = chat_info.encode(‘utf-8’)
Open the file for writing with UTF-8 encoding
with open(‘chats.txt’, ‘wb’) as chats_file:
chats_file.write(utf8_chat_info)
please I am really new
Did you install a package for handling Telegram? What’s it called? Where did you get it?
Without further details, we can’t help you.
here’s the content of the package.
import time
import asyncio
from telethon.sync import TelegramClient
class TelegramForwarder:
def init(self, api_id, api_hash, phone_number):
self.api_id = api_id
self.api_hash = api_hash
self.phone_number = phone_number
self.client = TelegramClient(‘session_’ + phone_number, api_id, api_hash)
async def list_chats(self):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
# Get a list of all the dialogs (chats)
dialogs = await self.client.get_dialogs()
chats_file = open(f"chats_of_{self.phone_number}.txt", "w")
# Print information about each chat
for dialog in dialogs:
print(f"Chat ID: {dialog.id}, Title: {dialog.title}")
chats_file.write(f"Chat ID: {dialog.id}, Title: {dialog.title} \n")
print("List of groups printed successfully!")
async def forward_messages_to_channel(self, source_chat_id, destination_channel_id, keywords):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
last_message_id = (await self.client.get_messages(source_chat_id, limit=1))[0].id
while True:
print("Checking for messages and forwarding them...")
# Get new messages since the last checked message
messages = await self.client.get_messages(source_chat_id, min_id=last_message_id, limit=None)
for message in reversed(messages):
# Check if the message text includes any of the keywords
if keywords:
if message.text and any(keyword in message.text.lower() for keyword in keywords):
print(f"Message contains a keyword: {message.text}")
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
else:
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
# Update the last message ID
last_message_id = max(last_message_id, message.id)
# Add a delay before checking for new messages again
await asyncio.sleep(5) # Adjust the delay time as needed
Function to read credentials from file
def read_credentials():
try:
with open(“credentials.txt”, “r”) as file:
lines = file.readlines()
api_id = lines[0].strip()
api_hash = lines[1].strip()
phone_number = lines[2].strip()
return api_id, api_hash, phone_number
except FileNotFoundError:
print(“Credentials file not found.”)
return None, None, None
Function to write credentials to file
def write_credentials(api_id, api_hash, phone_number):
with open(“credentials.txt”, “w”) as file:
file.write(api_id + “\n”)
file.write(api_hash + “\n”)
file.write(phone_number + “\n”)
async def main():
# Attempt to read credentials from file
api_id, api_hash, phone_number = read_credentials()
# If credentials not found in file, prompt the user to input them
if api_id is None or api_hash is None or phone_number is None:
api_id = input("Enter your API ID: ")
api_hash = input("Enter your API Hash: ")
phone_number = input("Enter your phone number: ")
# Write credentials to file for future use
write_credentials(api_id, api_hash, phone_number)
forwarder = TelegramForwarder(api_id, api_hash, phone_number)
print("Choose an option:")
print("1. List Chats")
print("2. Forward Messages")
choice = input("Enter your choice: ")
if choice == "1":
await forwarder.list_chats()
elif choice == "2":
source_chat_id = int(input("Enter the source chat ID: "))
destination_channel_id = int(input("Enter the destination chat ID: "))
print("Enter keywords if you want to forward messages with specific keywords, or leave blank to forward every message!")
keywords = input("Put keywords (comma separated if multiple, or leave blank): ").split(",")
await forwarder.forward_messages_to_channel(source_chat_id, destination_channel_id, keywords)
else:
print("Invalid choice")
Start the event loop and run the main function
if name == “main”:
asyncio.run(main())
import time
import asyncio
from telethon.sync import TelegramClient
class TelegramForwarder:
def __init__(self, api_id, api_hash, phone_number):
self.api_id = api_id
self.api_hash = api_hash
self.phone_number = phone_number
self.client = TelegramClient('session_' + phone_number, api_id, api_hash)
async def list_chats(self):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
# Get a list of all the dialogs (chats)
dialogs = await self.client.get_dialogs()
chats_file = open(f"chats_of_{self.phone_number}.txt", "w")
# Print information about each chat
for dialog in dialogs:
print(f"Chat ID: {dialog.id}, Title: {dialog.title}")
chats_file.write(f"Chat ID: {dialog.id}, Title: {dialog.title} \n")
print("List of groups printed successfully!")
async def forward_messages_to_channel(self, source_chat_id, destination_channel_id, keywords):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
last_message_id = (await self.client.get_messages(source_chat_id, limit=1))[0].id
while True:
print("Checking for messages and forwarding them...")
# Get new messages since the last checked message
messages = await self.client.get_messages(source_chat_id, min_id=last_message_id, limit=None)
for message in reversed(messages):
# Check if the message text includes any of the keywords
if keywords:
if message.text and any(keyword in message.text.lower() for keyword in keywords):
print(f"Message contains a keyword: {message.text}")
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
else:
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
# Update the last message ID
last_message_id = max(last_message_id, message.id)
# Add a delay before checking for new messages again
await asyncio.sleep(5) # Adjust the delay time as needed
# Function to read credentials from file
def read_credentials():
try:
with open("credentials.txt", "r") as file:
lines = file.readlines()
api_id = lines[0].strip()
api_hash = lines[1].strip()
phone_number = lines[2].strip()
return api_id, api_hash, phone_number
except FileNotFoundError:
print("Credentials file not found.")
return None, None, None
# Function to write credentials to file
def write_credentials(api_id, api_hash, phone_number):
with open("credentials.txt", "w") as file:
file.write(api_id + "\n")
file.write(api_hash + "\n")
file.write(phone_number + "\n")
async def main():
# Attempt to read credentials from file
api_id, api_hash, phone_number = read_credentials()
# If credentials not found in file, prompt the user to input them
if api_id is None or api_hash is None or phone_number is None:
api_id = input("Enter your API ID: ")
api_hash = input("Enter your API Hash: ")
phone_number = input("Enter your phone number: ")
# Write credentials to file for future use
write_credentials(api_id, api_hash, phone_number)
forwarder = TelegramForwarder(api_id, api_hash, phone_number)
print("Choose an option:")
print("1. List Chats")
print("2. Forward Messages")
choice = input("Enter your choice: ")
if choice == "1":
await forwarder.list_chats()
elif choice == "2":
source_chat_id = int(input("Enter the source chat ID: "))
destination_channel_id = int(input("Enter the destination chat ID: "))
print("Enter keywords if you want to forward messages with specific keywords, or leave blank to forward every message!")
keywords = input("Put keywords (comma separated if multiple, or leave blank): ").split(",")
await forwarder.forward_messages_to_channel(source_chat_id, destination_channel_id, keywords)
else:
print("Invalid choice")
# Start the event loop and run the main function
if __name__ == "__main__":
asyncio.run(main())
Hello Paul,
as you suggested here is my code.
Please let me know if i did the right way.
Thanks
Where is the code where you enter the special character. The special character is not entered in this module.
I see that chats_file
is a file opened on line 24:
chats_file = open(f"chats_of_{self.phone_number}.txt", "w")
It’s not specifying the encoding of the file, so it’s defaulting to cp1252
, which causes a problem later when writing a string that contains a character that’s not available in cp1252
.
The solution is to specify a suitable encoding, which, these days, really should be UTF-8
, so change that line to:
chats_file = open(f"chats_of_{self.phone_number}.txt", "w", encoding="utf-8")
what do you mean.
you mean the file that I am trying to run?
import asyncio
from telethon.sync import TelegramClient
class TelegramForwarder:
def __init__(self, api_id, api_hash, phone_number):
self.api_id = api_id
self.api_hash = api_hash
self.phone_number = phone_number
self.client = TelegramClient('session_' + phone_number, api_id, api_hash)
async def list_chats(self):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
# Get a list of all the dialogs (chats)
dialogs = await self.client.get_dialogs()
chats_file = open(f"chats_of_{self.phone_number}.txt", "w")
# Print information about each chat
for dialog in dialogs:
print(f"Chat ID: {dialog.id}, Title: {dialog.title}")
chats_file.write(f"Chat ID: {dialog.id}, Title: {dialog.title} \n")
print("List of groups printed successfully!")
async def forward_messages_to_channel(self, source_chat_id, destination_channel_id, keywords):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
last_message_id = (await self.client.get_messages(source_chat_id, limit=1))[0].id
while True:
print("Checking for messages and forwarding them...")
# Get new messages since the last checked message
messages = await self.client.get_messages(source_chat_id, min_id=last_message_id, limit=None)
for message in reversed(messages):
# Check if the message text includes any of the keywords
if keywords:
if message.text and any(keyword in message.text.lower() for keyword in keywords):
print(f"Message contains a keyword: {message.text}")
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
else:
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
# Update the last message ID
last_message_id = max(last_message_id, message.id)
# Add a delay before checking for new messages again
await asyncio.sleep(5) # Adjust the delay time as needed
# Function to read credentials from file
def read_credentials():
try:
with open("credentials.txt", "r") as file:
lines = file.readlines()
api_id = lines[0].strip()
api_hash = lines[1].strip()
phone_number = lines[2].strip()
return api_id, api_hash, phone_number
except FileNotFoundError:
print("Credentials file not found.")
return None, None, None
# Function to write credentials to file
def write_credentials(api_id, api_hash, phone_number):
with open("credentials.txt", "w") as file:
file.write(api_id + "\n")
file.write(api_hash + "\n")
file.write(phone_number + "\n")
async def main():
# Attempt to read credentials from file
api_id, api_hash, phone_number = read_credentials()
# If credentials not found in file, prompt the user to input them
if api_id is None or api_hash is None or phone_number is None:
api_id = input("Enter your API ID: ")
api_hash = input("Enter your API Hash: ")
phone_number = input("Enter your phone number: ")
# Write credentials to file for future use
write_credentials(api_id, api_hash, phone_number)
forwarder = TelegramForwarder(api_id, api_hash, phone_number)
print("Choose an option:")
print("1. List Chats")
print("2. Forward Messages")
choice = input("Enter your choice: ")
if choice == "1":
await forwarder.list_chats()
elif choice == "2":
source_chat_id = int(input("Enter the source chat ID: "))
destination_channel_id = int(input("Enter the destination chat ID: "))
print("Enter keywords if you want to forward messages with specific keywords, or leave blank to forward every message!")
keywords = input("Put keywords (comma separated if multiple, or leave blank): ").split(",")
await forwarder.forward_messages_to_channel(source_chat_id, destination_channel_id, keywords)
else:
print("Invalid choice")
# Start the event loop and run the main function
if __name__ == "__main__":
asyncio.run(main())```
In your original code you gave the following error.
But in this file, when performing a search, this special character is not found. Where is the script snippet where it is entered?
Please also do as @MRAB stated in his post:
Specifically state the encoding type as the default might be different.
Hello Matthew should I add this to my file?
Hello Paul,
honestly I don’t know here’s where I downloaded the file
https://github.com/redianmarku/Telegram-Autoforwarder.git
I follow one youtube video.
https://www.youtube.com/watch?v=Ae8d4rAwmEk&t=68s
I am trying to auto forward telegram message