In general, I want to achieve the result of automatic infinite mailing with a delay of a certain number of seconds, as well as an autoresponder to personal messages 30 seconds after I received it.
And also - that the messages about the sent mailing will be broadcast in my telegram channel, as well as to receive reports about what message was sent to me.
Yes, confusing, but I seem to have written something, but not correctly, please help.
import asyncio
from telethon.sync import TelegramClient, events
API_ID = 22133720
API_HASH = "08af2f4d9e4c65cb242d230e533338e8"
target_chat_usernames = ['@hindi_english_group_chatting', '@usa_groups_chat', '@USAjiaoyou'] # Your target chat usernames
text_messages = [
"Hey, folks! How's everyone doing?",
"Hello, everyone! How was your day?",
"Hello, chat buddies! Perhaps someone here wants to share their hobbies or simply engage in a conversation?"
]
text_message_index = 0
messages_sent = 0
async def send_auto_reply(event, client):
await event.reply("Thank you for your message! I'm currently busy but will get back to you soon.")
async def main():
async with TelegramClient('anon', API_ID, API_HASH) as client:
report_channel_username = '@jabro45dilak78'
report_channel_entity = await client.get_entity(report_channel_username)
@client.on(events.NewMessage(chats=target_chat_usernames))
async def respond_to_message(event):
await send_auto_reply(event, client)
while True:
try:
await asyncio.sleep(20)
for target_chat_username in target_chat_usernames:
try:
target_chat_entity = await client.get_entity(target_chat_username)
text_message = text_messages[text_message_index]
sent_message = await client.send_message(target_chat_entity, text_message)
messages_sent += 1
text_message_index = (text_message_index + 1) % len(text_messages)
print(f"Message sent to chat {target_chat_username}: {text_message}")
except ValueError as e:
if "No user has" in str(e):
print(f"User not found in chat {target_chat_username}, skipping...")
else:
raise e
except Exception as e:
print(f"An error occurred: {e}")
continue
finally:
try:
await client.send_message(report_channel_entity, f"Messages sent: {messages_sent}")
print(f"Report sent to {report_channel_username}")
except Exception as e:
print(f"Failed to send report: {e}")
if __name__ == "__main__":
asyncio.run(main())
Errors - the code does not work fully, it lacks the rhythm of infinity - it stops.
It does not send any reports to the channel.
The autoresponder replies in the general chat immediately, although it should reply to private messages 30 seconds after sending.
Unresolved reference 'messages_sent' :37 Unresolved reference 'messages_sent' :50
An error occurred: cannot access local variable 'text_message_index' where it is not associated with a value Failed to send report: cannot access local variable 'messages_sent' where it is not associated with a value Failed to send report: cannot access local variable 'messages_sent' where it is not associated with a value Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\User\Desktop\mySPORTspam\bot text spam chat automessage\textspam.py", line 31, in main await asyncio.sleep(20) File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 639, in sleep return await future ^^^^^^^^^^^^ asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\User\Desktop\mySPORTspam\bot text spam chat automessage\textspam.py", line 56, in asyncio.run(main()) File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 123, in run raise KeyboardInterrupt() KeyboardInterrupt