Skip to content

Commit

Permalink
more error handling and logging; bug fixes; move configuration to .env
Browse files Browse the repository at this point in the history
  • Loading branch information
Z1xus committed Nov 3, 2023
1 parent d977a00 commit 78925c7
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 33 deletions.
16 changes: 16 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# in case you got rate limited
USE_PROXY=False
PROXY=http://localhost:8080

# channel ids where the bot listens for messages
ALLOWED_IDS=1234567890123456789,...

# reactions list in unicode, emoji and escape formats
REACTIONS=🇧,🇮,🇹,🇨,🇭

# random delay range in seconds
MIN_DELAY=1
MAX_DELAY=5

# your discord user token, see https://www.androidauthority.com/get-discord-token-3149920/
USER_TOKEN=
65 changes: 44 additions & 21 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,58 @@
import discord
import random
import asyncio
import logging
import os
from dotenv import load_dotenv
from asyncio import Semaphore, Queue

# in case you got rate limited
use_proxy = False
proxy = "http://localhost:8080"

# channel ids where the bot listens for messages
allowed_ids = [1234567890123456789, ...]

# reactions list in unicode, emoji and escape formats
reactions = ["🇧", "🇮", "🇹", "🇨", "🇭"]
if os.path.exists('.env'):
load_dotenv()
else:
logging.error('No .env file found.')

# random delay range in seconds
min_delay = 1
max_delay = 5
# since v1.0.3 configuration was moved to .env

# change your user token
user_token = "..."
use_proxy = os.getenv('USE_PROXY') == 'True'
proxy = os.getenv('PROXY')
allowed_ids = list(map(int, os.getenv('ALLOWED_IDS').split(',')))
reactions = os.getenv('REACTIONS').split(',')
min_delay = int(os.getenv('MIN_DELAY'))
max_delay = int(os.getenv('MAX_DELAY'))
user_token = os.getenv('USER_TOKEN')

semaphore = Semaphore(5)

if use_proxy:
client = discord.Client(proxy=proxy)
client = discord.Client(chunk_guild_at_startup=False, proxy=proxy)
print(f"Using proxy: {proxy}")
else:
client = discord.Client()
client = discord.Client(chunk_guild_at_startup=False)

message_queue = Queue()

async def add_reactions(message):
async with semaphore:
message_deleted = False
for reaction in reactions:
if message_deleted:
break
try:
await message.add_reaction(reaction)
delay = random.randint(min_delay, max_delay)
await asyncio.sleep(delay)
except discord.errors.NotFound:
print("Message not found. Skipping reaction.")
logging.error("Message not found. Skipping reactions.")
message_deleted = True
except discord.errors.Forbidden:
logging.error("Permisssions error. Skipping reactions.")
message_deleted = True
except discord.errors.HTTPException:
logging.warning("Rate limit or network error. Retrying after delay.")
await asyncio.sleep(10)
await message.add_reaction(reaction)
except Exception as e:
print(f"An error occurred while adding reaction: {e}")
logging.exception(f"An unexpected error occurred while adding reaction: {e}")

async def process_messages():
while True:
Expand All @@ -55,13 +67,24 @@ async def on_message(message):

@client.event
async def on_ready():
print(f"Logged in as {client.user}")
asyncio.create_task(process_messages())
try:
print(f"Logged in as {client.user}")
asyncio.create_task(process_messages())
except discord.LoginFailure:
logging.warning("Login failed. Make sure you're using a valid user token.")
except Exception as e:
logging.exception(f"An error occurred while running the bot: {e}")

try:
if not user_token:
raise ValueError('No user token provided')
loop = asyncio.get_event_loop()
loop.run_until_complete(client.start(user_token))
except ValueError as ve:
logging.error(ve)
except discord.LoginFailure:
logging.error("Login failed. Make sure you're using a valid user token.")
except KeyboardInterrupt:
print("\nCtrl+C received, exiting...")
except Exception as e:
print(f"An error occurred while running the bot: {e}")
logging.exception(f"An error occurred while running the bot: {e}")
22 changes: 11 additions & 11 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,26 +23,26 @@ git clone https://github.com/Z1xus/self-reaction-bot
```
2. Install dependencies
```bash
pip install -r .\requirements.txt
pip install -r .\requirements.txt -U
```
3. Configure the bot
```python
3. Configure your .env
```Shell
# in case you got rate limited
use_proxy = False
proxy = "http://localhost:8080"
USE_PROXY=False
PROXY=http://localhost:8080

# channel ids where the bot listens for messages
allowed_ids = [1234567890123456789, ...]
ALLOWED_IDS=1234567890123456789,...

# reactions list in unicode, emoji and escape formats
reactions = ["🇧", "🇮", "🇹", "🇨", "🇭"]
REACTIONS=🇧,🇮,🇹,🇨,🇭

# random delay range in seconds
min_delay = 1
max_delay = 5
MIN_DELAY=1
MAX_DELAY=5

# change yo user token
user_token = "..."
# your discord user token, see https://www.androidauthority.com/get-discord-token-3149920/
USER_TOKEN=
```
4. Run it
```bash
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
discord.py-self>=2.0.0
discord.py-self==2.0.0
python-dotenv>=1.0.0

0 comments on commit 78925c7

Please sign in to comment.