So I have bot. Bot has many event listeners and text.commands. It was working fine for 2-3 mouth. But suddenly bot’s @bot.command stop working in all channels except #bot-command. All event listener functions are working perfectly in all channels.
code is too big to paste here so i am goona post only few commands here. If you can’t understand the function logic or unexist varables than they too exit but i didn’t include all the thing due to personal reasons.
import os
import discord
from discord.ext import commands
#import re
#import shutil
from PIL import Image, ImageOps, ImageDraw, ImageFont
import asyncio
import imagehash #< Find Command >
import io
from aiohttp.client_exceptions import ClientConnectorError
import hashlib
#from typing import Union
from discord import TextChannel
from io import BytesIO
#------------------------------------------------------------------------------------------------------------------------------------------------------
TOKEN = 'hidden'
WINDOWS_FOLDER_PATH = DownlaodL_Folder = r'D:/Personal/Auto upload/xyz'
TEMP_FOLDER_PATH = r'D:/Personal/Auto upload/temp'
intents = discord.Intents.all()
client = discord.Client(intents=intents)
intents.guild_reactions = True
intents.message_content = True
intents.messages = True
intents.typing = True
bot = commands.Bot(command_prefix='-', intents=intents)
upload_folder = DownlaodL_Folder
#------------------------------------------------------------------------------------------------------------------------------------
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user.name}')
pinboard_channel_id = 1133687265575583897
pin_emoji = '📌'
pinned_messages = {} # Dictionary to track pinned messages in the pins channel
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user.name}')
pin_mapping_ID = 1225919783036391455 #Mapping
reaction_emoji = "📍"
#=========================================================================================================< pin even listner>==============
@bot.event
async def on_raw_reaction_add(payload):
print(f"{payload.emoji} reaction ADDED")
if payload.emoji.name in ['🚫', '📍', '❌', '⭕', '🎨', '✨']:
channel = bot.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
attachment = None
for reaction in message.reactions:
print(f"The emoji {reaction.emoji} was reacted to the message.")
if reaction.emoji in [
'0️⃣', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣'
]:
index = int(reaction.emoji[0])
if index < len(message.attachments):
attachment = message.attachments[index]
print(f"{index}th attachment")
break
if not attachment:
attachment = message.attachments[0]
filename = attachment.filename
eeveelutions_channels = [
1108404188217606185, 1108404133532274821, 1108405021793595392,
1108405217235579011, 1132591490997162064, 1108405328720179361,
1108405437189066796, 1108405797077123183, 1108405645612421231
]
# Determine the target channels based on the conditions
target_channels = []
if payload.emoji.name == '🚫':
target_channels.append(bot.get_channel(1142465680927629414))
i_channel_id = 0
elif payload.emoji.name == '✨':
target_channels.append(bot.get_channel(1133687265575583897))
i_channel_id = 1133687265575583897
# Determine the target channel based on the original message's channel
if payload.emoji.name == '✨':
if channel.id == 1108405932859346974:
target_channels.append(bot.get_channel(1217915359659688016))
elif channel.id == 1108404097146704003:
target_channels.append(bot.get_channel(1155273109901951106))
elif channel.id in fdydy_channels:
target_channels.append(
bot.get_channel(1155273326411923527))
if payload.emoji.name in ['📍', '❌', '⭕', '🎨']:
if payload.emoji.name == '📍':
target_channels.append(
bot.get_channel(1141310866650841088))
if channel.id == 1108406229035925655 or channel.id == 1108406154498941029:
target_channels.append(
bot.get_channel(1231374594334658563))
elif channel.id in [1132202502444556459, 1132202552436457542]:
target_channels.append(
bot.get_channel(1230252388032712735))
if payload.emoji.name == '❌':
target_channels.append(
bot.get_channel(1141374405780455454))
if payload.emoji.name == '⭕':
target_channels.append(
bot.get_channel(1135926589792731176))
if payload.emoji.name == '🎨':
target_channels.append(
bot.get_channel(1135926645748940821))
for target_channel in target_channels:
if target_channel or isinstance(target_channel, discord.Thread):
attachment_url = attachment.url
content = message.content
message_link = message.jump_url
filename_without_extension = filename.split(".")[0][:46]
value = f"[{filename_without_extension}]({message_link})\n{content}"
embed = discord.Embed(description=value, color=discord.Color.blue())
embed.set_image(url=attachment_url)
# If the target channel is a thread, send the message to the thread
if isinstance(target_channel, discord.Thread):
sent_message = await target_channel.send(content="", embed=embed)
print(f"Embed Successfully to Thread(ID): {target_channel.id}")
else:
sent_message = await target_channel.send(embed=embed)
print(f"Embed Successfully to channel(ID): {target_channel.id}")
# Store the message IDs in the mapping channel
mapping_channel = bot.get_channel(pin_mapping_ID)
if mapping_channel:
await mapping_channel.send(
f"{payload.message_id}:{sent_message.id}:{target_channel.id}")
else:
print(f"Target channel {target_channel} not found")
@bot.event
async def on_raw_reaction_remove(payload):
print(f"------<> {payload.emoji} reaction REMOVED <>-------")
if payload.emoji.name in ['📌', '🚫', '📍', '❌', '⭕', '🎨', '✨']:
mapping_channel = bot.get_channel(pin_mapping_ID)
temp = 0
removed = 0
if mapping_channel:
async for message in mapping_channel.history(limit=None):
temp = temp + 1
mapping = message.content.split(":")
print(f"mapping msg founded {temp}: {message.content}")
if mapping[0] == str(payload.message_id):
print(f"message: {int(mapping[0])}")
if int(
mapping[2]
) != 1135926589792731176 and payload.emoji.name == '⭕' or int(
mapping[2]) == 1135926589792731176 and payload.emoji.name in [
'📌', '🚫', '📍', '❌', '🎨', '✨'
]:
continue
if int(
mapping[2]
) != 1142465680927629414 and payload.emoji.name == '🚫' or int(
mapping[2]) == 1142465680927629414 and payload.emoji.name != '🚫':
continue
if int(
mapping[2]
) != 1135926645748940821 and payload.emoji.name == '🎨' or int(
mapping[2]) == 1135926645748940821 and payload.emoji.name != '🎨':
continue
if payload.emoji.name == '✨' and int(
mapping[2]) == 1135926645748940821:
continue
else:
target_channel_id = int(mapping[2])
target_channel = bot.get_channel(target_channel_id)
if target_channel:
embed_message = await target_channel.fetch_message(int(mapping[1]))
if embed_message:
await message.delete()
await embed_message.delete()
removed = removed + 1
continue
else:
print(
f"embed not found: {int (mapping[1])} deleting mapping msg")
await message.delete()
continue
print(f"------> Total embed removed: {removed} <-------")
else:
print(f"Mapping channel not found")
#-s a b !c !!excludded_channels =included_channels===========================================================================================< search command >========
async def send_result(ctx, results, total_results, message_parts):
if results:
results.sort(key=lambda x: x[4])
for result in results:
filename, content, attachment_url, message_link, timestamp, emotes = result
embed = discord.Embed()
filename_without_extension = filename.split(".")[0][:46]
if emotes:
emote_str = ", ".join(emotes)
value = f"[{filename_without_extension} {emote_str}]({message_link})\n{content}"
else:
value = f"[{filename_without_extension}]({message_link})\n{content}"
embed = discord.Embed(description=value, color=discord.Color.red())
embed.set_image(url=attachment_url)
await ctx.send(embed=embed)
# Check if it's the last result
if total_results > 0 and results[-1][4] == results[-1][4]:
return True
return False
@bot.command()
async def s(ctx, *keywords):
await ctx.channel.purge(limit=1)
results = []
total_results = 0
included_channels = set()
excluded_channels = set()
required_keywords = set()
excluded_keywords = set(["_vid", "-set", "_pin_"])
include_next_keyword = True
for keyword in keywords:
if keyword.startswith('?'):
# include_next_keyword = False
excluded_keyword = keyword[1:].lower()
if excluded_keyword not in excluded_keywords:
excluded_keywords.add(excluded_keyword)
elif keyword.startswith('='):
if keyword.startswith('=') :
excluded_keywords.discard("-asasa")
included_channels.add(keyword[1:])
else:
included_channels.add(keyword[1:])
# include_next_keyword = False
elif keyword.startswith('!'):
excluded_channels.add(keyword[1:])
elif keyword.lower() == "abc":
excluded_keywords.remove("vyz")
included_channels.add("abc")
elif keyword.lower() == "opo":
included_channels.add("opo")
elif keyword.lower() == "asasas":
temp = ["qwe"]
excluded_channels.update(temp)
else:
if include_next_keyword:
required_keywords.add(keyword)
else:
include_next_keyword = True
searched_channels = 0
server_channels = sum(1 for _ in ctx.guild.text_channels)
print(f"Total server channels: {server_channels}")
excluded_keywords -= required_keywords
message_parts = []
if required_keywords:
message_parts.append(
f"```{', '.join(required_keywords)}``` excluding ```{', '.join(excluded_keywords)}```"
)
if included_channels:
message_parts.append(f"in {', '.join(included_channels)}")
if excluded_channels:
message_parts.append(f"except in {', '.join(excluded_channels)}")
if not message_parts:
await ctx.send("No search criteria provided.")
else:
if required_keywords:
await ctx.send(f"Searching files for {', '.join(message_parts)}.")
else:
await ctx.send(f"Searching all files {', '.join(message_parts)}.")
required_keywords = {keyword.lower() for keyword in required_keywords}
temp = [
"pins", "general", "bot-commands", "🎨¦fav-artist", "fav-videos", "mappings"
]
excluded_channels.update(temp)
for guild in bot.guilds:
for channel in guild.text_channels:
searched_channels += 1
#show progress, commented for now
# print(f"Channel: {channel.name} ({searched_channels}),Progress: {searched_channels / server_channels}")
if searched_channels / server_channels == 0.5:
await asyncio.sleep(1)
await ctx.send("Half of the server searched.")
if searched_channels / server_channels >= 0.8 and searched_channels / server_channels < 0.82:
await asyncio.sleep(1)
await ctx.send("80% of the server searched.")
if channel.name not in excluded_channels:
if not included_channels or channel.name in included_channels:
print(f"In Channel: {channel.name}")
# Fetch messages and use list comprehension
messages = [message async for message in channel.history(limit=None)]
for message in reversed(messages):
if message.attachments:
for attachment in message.attachments:
if all(keyword in attachment.filename.lower()
for keyword in required_keywords):
if any(keyword in attachment.filename.lower()
for keyword in excluded_keywords):
continue
emotes = []
for reaction in message.reactions:
emote_str = str(reaction.emoji)
emotes.append(emote_str)
results.append(
(attachment.filename, message.content, attachment.url,
message.jump_url, message.created_at, emotes))
# Send the result immediately with sorting
results.sort(key=lambda x: x[4])
total_results += 1
await send_result(ctx, results, total_results, message_parts)
# Clear results for the next iteration
results = []
await ctx.send(
f"Total result for {', '.join(message_parts)} = {total_results}. ")
print(f"Total Search Results = {total_results}")
#=====================================================================================================================================< Duplicate Even Listner >========
async def is_image(file_bytes):
try:
Image.open(BytesIO(file_bytes)).verify()
return True
except Exception:
return False
async def calculate_phash(file_bytes):
try:
image = Image.open(BytesIO(file_bytes))
phash = imagehash.phash(image)
return str(phash)
except Exception as e:
print(f"Error opening image: {e}")
return None
async def check_for_duplicates(file_bytes, message, founded):
blacklisted_channels = [
"pins", "general", "bot-commands", "🎨¦fav-artist", "fav-videos", "mappings"
]
if not await is_image(file_bytes):
print("The attachment is not recognized as an image.")
return
phash = await calculate_phash(file_bytes)
if phash is None:
print("Unable to calculate perceptual hash for the image.")
return
channels_searched = 0
messages_processed = 0
# Search the channel where the message was sent
print("------<> Auto Duplicate Image Detection is triggered <>-------")
channels_searched += 1
if founded == 0:
await message.add_reaction('📥')
async for msg in message.channel.history(limit=None):
messages_processed += 1
if msg.attachments:
for msg_attachment in msg.attachments:
if not await is_image(await msg_attachment.read()):
continue
phash_attachment = await calculate_phash(await msg_attachment.read())
if phash_attachment is None:
continue
if phash == phash_attachment:
founded += 1
if founded != 1:
await message.channel.send(
f"{founded - 1} Duplicate files found in #{message.channel.name} -> ```{msg_attachment.filename}``` {msg.jump_url}"
)
print(f"{founded - 1} Duplicate files found")
if messages_processed % 50 == 0:
print(
f"Processed {messages_processed} messages. Current Channel: {message.channel.name} so far..."
)
if messages_processed % 800 == 0:
print(f"Sleeping for 10 sec")
await asyncio.sleep(10)
# Search the rest of the server's channels from top to bottom
await message.clear_reaction('📥')
for channel in message.guild.channels:
if channel == message.channel:
continue
await message.add_reaction('📤')
if isinstance(channel, discord.TextChannel) and channel.name not in blacklisted_channels:
channels_searched += 1
async for msg in channel.history(limit=None):
messages_processed += 1
if msg.attachments:
for msg_attachment in msg.attachments:
if not await is_image(await msg_attachment.read()):
continue
phash_attachment = await calculate_phash(await msg_attachment.read())
if phash_attachment is None:
continue
if phash == phash_attachment:
founded += 1
if founded != 1:
await message.channel.send(
f"{founded - 1} Duplicate file found in {channel.name}: {msg.jump_url}"
)
if messages_processed % 50 == 0:
print(
f"Processed {messages_processed} messages. Current Channel: {channel.name} so far..."
)
if messages_processed % 800 == 0:
print(f"Sleeping for 10 sec")
await asyncio.sleep(10)
else:
print(f"Skipped Channel: {channel.name}")
await message.clear_reaction('📤')
print(f"----> Total channels searched: {channels_searched}. Total Duplicated Match: {founded - 1} <----")
founded = 0
@bot.event
async def on_message(message):
attempt = 0
founded = 0
blacklisted_channels = ["bot-commands", "general", "t1"]
if message.channel.name in blacklisted_channels:
await bot.process_commands(message)
return
try:
if message.attachments:
for attachment in message.attachments:
if "_pin_" in attachment.filename:
continue
await check_for_duplicates(await attachment.read(), message, founded)
# Process other commands
await bot.process_commands(message)
except Exception as e:
print(f"Error occurred: {e}")
await asyncio.sleep(30)
attempt += 1
if attempt < 4:
print(f" Retrying... Attempt {attempt} of 3 ")
await check_for_duplicates(await attachment.read(), message, founded) # Retry by calling on_message again
await bot.process_commands(message)
else:
print("------> Retry limit reached. Unable to process further. <-------")
founded = 0
await bot.process_commands(message)
#=====< delete messages >====================================================================================< Purge Command >=================
@bot.command()
async def purge(ctx, limit: int):
await ctx.message.delete() # Delete the command message
await ctx.channel.purge(limit=limit)
await ctx.send(f"Massages Purge: {limit}")
print(f"Massages Purge: {limit}")
bot.run(TOKEN)