I'm trying to make a discord bot but the bot is not responding to any of my commands.
He is writing the command when going online but nothing more.
I have given him every permission and intent but it did not help.
import discord
import time
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
# Dictionary to store the brake times for each user
brb_times = {}
#client.event
async def on_message(message):
# Only process messages from other users, not the bot itself
if message.author == client.user:
return
if message.content.startswith("!brb 5"):
brb_times[message.author.name] = time.time() + 5 * 60
await message.channel.send(f"{message.author.mention} has taken a 5-minute brake.")
elif message.content.startswith("!brb 10"):
brb_times[message.author.name] = time.time() + 10 * 60
await message.channel.send(f"{message.author.mention} has taken a 10-minute brake.")
elif message.content.startswith("!brb 15"):
brb_times[message.author.name] = time.time() + 15 * 60
await message.channel.send(f"{message.author.mention} has taken a 15-minute brake.")
elif message.content.startswith("!back"):
if message.author.name in brb_times:
brake_time = brb_times[message.author.name]
del brb_times[message.author.name]
elapsed_time = time.time() - brake_time
if elapsed_time > 0:
await message.channel.send(f"{message.author.mention} is back, but was late by {int(elapsed_time)} seconds.")
else:
await message.channel.send(f"{message.author.mention} is back.")
else:
await message.channel.send(f"{message.author.mention} was not on a brake.")
#client.event
async def on_ready():
print("Bot is ready!")
await client.get_channel(CENSORED).send("Bot is ready to track breaks!")
client.run("CENSORED")
You need message_content to be True in intents.
Related
This is an anti spam code to prevent spams and stuff.
time_window_milliseconds = 5000
max_msg_per_window = 5
author_msg_times = {}
# Struct:
# {
# "<author_id>": ["<msg_time", "<msg_time>", ...],
# "<author_id>": ["<msg_time"],
# }
#client.event
async def on_message(message):
global author_msg_counts
author_id = message.author.id
# Get current epoch time in milliseconds
curr_time = datetime.now().timestamp() * 1000
# Make empty list for author id, if it does not exist
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
# Append the time of this message to the users list of message times
author_msg_times[author_id].append(curr_time)
# Find the beginning of our time window.
expr_time = curr_time - time_window_milliseconds
# Find message times which occurred before the start of our window
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
# Remove all the expired messages times from our list
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
# ^ note: we probably need to use a mutex here. Multiple threads
# might be trying to update this at the same time. Not sure though.
if len(author_msg_times[author_id]) > max_msg_per_window:
await message.channel.send(f"{message.author.mention} stop spamming or i will mute you 😡")
await asyncio.sleep(4)
await message.channel.send(f"{message.author.mention} stop spamming or i will mute you 😡")
muted = discord.utils.get(message.guild.roles, name="Muted")
if not muted:
muted = await message.guild.create_role(name="Muted")
await message.author.send(f"You have been muted in {message.guild.name} for spamming | You'll be unmuted in 10 minutes.")
await message.author.add_roles(muted)
await message.channel.send(f"{message.author.mention} have been muted for 10 minutes.")
await asyncio.sleep(600)
await message.channel.send(f"{message.author.mention} have been unmuted | Reason: Time is over. ")
await message.author.remove_roles(muted)
await message.author.send(f"You have been unmuted from {message.guild.name}")
Hey guys, I'm getting an error here. It works OK, but when someone keeps spamming, the bot keeps spamming, and it becomes a mess. After about a minute, the bot keeps spamming, so stop spamming or I'll mute you.
You need to exclude your own bots messages in the event. So just this should work:
#client.event
async def on_message(message):
if message.author == client.user:
return
#rest of your code
Hello I have been trying to create a application bot for my server the bot sends you a questions then the person answers then its noted down ect but my problem is that sometimes the next question would send without waiting for the answer to the previous question. this only happens most of the time. try i might i have not been able to fix the problem. I’m pretty new to python and at the end of my wits.
my code for reference:
import os
from discord.ext import commands
from discord.utils import get
BOT_PREFIX = ("!")
client = commands.Bot(command_prefix=BOT_PREFIX)
a_list = []
#client.event
async def on_ready():
print ("------------------------------------")
print ("Bot Name: " + client.user.name)
print ("------------------------------------")
submit_wait = False
a_list = []
b_list = []
c_list = []
d_list = []
#client.command(aliases=['application'])
async def app(ctx):
a_list = []
b_list = []
c_list = []
d_list = []
submit_wait = False
submit_channel = client.get_channel(806404345830047744)
channel = await ctx.author.create_dm()
await channel.send("starting applaction!")
await ctx.send(ctx.author.mention + "check your dms!")
time.sleep(2)
def check(m):
return m.content is not None and m.channel == channel
await channel.send("Do you have any prior milli sim experiance?")
msg = await client.wait_for('message', check=check)
a_list.append(msg.content)
await channel.send("What time zone are you in?")
msg2 = await client.wait_for('message', check=check)
b_list.append(msg2.content)
await channel.send("If a officer ordered you to break the genva convention would you do it?")
msg3 = await client.wait_for('message', check=check)
c_list.append(msg3.content)
await channel.send("Is there any particular dvision you want to be in?")
msg4 = await client.wait_for('message', check=check)
d_list.append(msg4.content)
await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
msg = await client.wait_for('message', check=check)
if "submit" in msg.content.lower():
submit_wait = False
answers = "\n".join(f'{a}. {b}' for a, b in enumerate(a_list, 1))
answer = "\n".join(f'{a}. {b}' for a, b in enumerate(b_list, 2))
answerr = "\n".join(f'{a}. {b}' for a, b in enumerate(c_list, 3))
answerss = "\n".join(f'{a}. {b}' for a, b in enumerate(d_list, 4))
submit_msg = f'Application from {msg.author} \nThe answers are:\n{answers}'
submit_msg2 = f'{answer}'
submit_msg3 = f'{answerr}'
submit_msg4 = f'{answerss}'
await submit_channel.send(submit_msg)
await submit_channel.send(submit_msg2)
await submit_channel.send(submit_msg3)
await submit_channel.send(submit_msg4)
client.run(os.getenv('TOKEN'))
I tested code using print() and I think problem is because check() sometimes gets bot's question and it treats it as user's answer.
You have to check m.author in check() - something like this
#client.command(aliases=['application'])
async def app(ctx):
submit_channel = client.get_channel(806404345830047744)
#print('submit_channel:', submit_channel)
channel = await ctx.author.create_dm()
author = ctx.author
def check(m):
#print('m.author:', m.author)
#print('m.content:', m.content)
#print('m.channel:', m.channel, m.channel == channel)
return m.author == author and m.content and m.channel == channel
Minimal working code with other changes
import os
import time
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print ("------------------------------------")
print ("Bot Name:", client.user.name)
print ("------------------------------------")
#client.command(aliases=['application'])
async def app(ctx):
submit_channel = client.get_channel(806404345830047744)
print('submit_channel:', submit_channel)
channel = await ctx.author.create_dm()
author = ctx.author
def check(m):
print('m.author:', m.author)
print('m.content:', m.content)
print('m.channel:', m.channel, m.channel == channel)
return m.author == author and m.content and m.channel == channel
await channel.send("starting applaction!")
await ctx.send(ctx.author.mention + " check your dms!")
time.sleep(2)
await channel.send("Do you have any prior milli sim experiance?")
answer_a = await client.wait_for('message', check=check)
answer_a = answer_a.content
await channel.send("What time zone are you in?")
answer_b = await client.wait_for('message', check=check)
answer_b = answer_b.content
await channel.send("If a officer ordered you to break the genva convention would you do it?")
answer_c = await client.wait_for('message', check=check)
answer_c = answer_c.content
await channel.send("Is there any particular dvision you want to be in?")
answer_d = await client.wait_for('message', check=check)
answer_d = answer_d.content
await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
msg = await client.wait_for('message', check=check)
if "submit" in msg.content.lower():
submit_msg = f'''Application from {msg.author}
The answers are:
1. {answer_a}
2. {answer_b}
3. {answer_c}
4. {answer_d}'''
await submit_channel.send(submit_msg)
client.run(os.getenv('TOKEN'))
Ok so at first glance I'm picking up a few errors
Firstly, minor issue, but using time.sleep(2) will pause your entire bot, so if you want to let other people to run this command at the same time you may want to change this
import asyncio # instead of import time
await asyncio.sleep(2) # instead of time.sleep(2)
Also you needn't repeat so much code, this should make it work exactly how you want it to
import os
from discord.ext import commands
from discord.utils import get
import asyncio
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print ("------------------------------------")
print ("Bot Name: " + client.user.name)
print ("------------------------------------")
submit_wait = False
questions = ["Do you have any prior milli sim experiance?",
"What time zone are you in?",
"If a officer ordered you to break the genva convention would you do it?",
"Is there any particular dvision you want to be in?"]
#client.command(aliases=['application'])
async def app(ctx):
submit_channel = client.get_channel(810118639234973719)
channel = await ctx.author.create_dm()
await channel.send("starting applaction!")
await ctx.send(ctx.author.mention + "check your dms!")
await asyncio.sleep(2)
def check(m):
return m.content != "" and m.channel == channel
answers = []
for question in questions:
await channel.send(question)
msg = await client.wait_for("message", check=check)
answers.append(msg.content)
await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
msg = await client.wait_for("message", check=check)
if "submit" in msg.content.lower():
submit_wait = False
answers = [f"{no+1}. {ans}" for no, ans in enumerate(answers)]
submit_msg = [f"Application from {msg.author}",
"The answers are:", *answers]
await submit_channel.send("\n".join(submit_msg))
client.run(os.getenv('TOKEN'))
I want that when someone reacts to one emoji the bot writes as a log on chat like this:
#Santa has press 4️⃣
I tried to make it but I'm stuck.
import discord
import time
import random
from discord.ext import commands
client = discord.Client()
bot = client.user
if message.content.startswith('ººrandgame'):
original = await message.channel.send('Discover the number I my mind...')
uno = await original.add_reaction('1️⃣')
dos = await original.add_reaction('2️⃣')
tres = await original.add_reaction('3️⃣')
cuatro = await original.add_reaction('4️⃣')
cinco = await original.add_reaction('5️⃣')
seis = await original.add_reaction('6️⃣')
siete = await original.add_reaction('7️⃣')
ocho = await original.add_reaction('8️⃣')
nueve = await original.add_reaction('9️⃣')
diez = await original.add_reaction('🔟')
numbers = ['1️⃣','2️⃣','3️⃣','4️⃣','5️⃣','6️⃣','7️⃣','8️⃣','9️⃣','🔟']
#this part fails::
if(reaction.emoji == "1️⃣"):
await message.channel.send(author + "has press 1️⃣")
#the same idea with the other numbers
time.sleep(15)
finalnum = random.choice(numbers)
await message.channel.send('My number is: ' + finalnum)
print(finalnum)
client.run('blabla')
You can use a reaction_wait_for, this will always wait for the author of the message input of the specified reaction.
Below I've made a simple user reaction command but I'll leave it up to you how you would further like to improve it.
message = await ctx.send("React to a number")
one = '1️⃣'
two = '2️⃣'
await message.add_reaction(one)
await message.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=600.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
In your code, I would also reccomend using asyncio.sleep(15) instead of time.sleep, as this causes the whole bot to stop, meaning no one can use it at all.
Make sure to import asyncio
You can also set it as a command, instead of using if message.content.startswith('ººrandgame'): , You can use
#client.command()
async def ººrandgame(ctx):
.... Rest of your code ...
Ibidem, I think that something is missing
import discord
import os
import random
import asyncio
from discord.ext import commands
client = discord.Client()
horaact = time.strftime('%H:%M:%S')
os.system('cls')
os.system('color 1f')
#client.event
async def on_ready():
print("Encendido")
print("logged in as {0.user}".format(client))
#client.command()
async def ººrandgame(ctx):
message = await ctx.send("React to a number")
one = '1️⃣'
two = '2️⃣'
await message.add_reaction(one)
await message.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=600.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
client.run('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
Remember, this is not the original code, it's just a test for trying your funtion
i have a question again :)
i plan a bot that will give a message output to a channel after a user has tell the bot when.
i will show you the code and then i will tell you my problem:
import discord
import datetime
import time
import asyncio
import random
from discord.ext import commands
from discord import Embed
TOKEN = 'mytoken'
intents = discord.Intents().all()
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(client.user.name)
print(client.user.id)
#client.event
async def on_message(message):
def check(m):
return m.channel == message.channel and m.author != client.user
if message.author == client.user:
return
if message.content.startswith("!start"):
await message.channel.send('Please type in the Enddate (TT.MM.JJ):')
enddateinput = await client.wait_for('message', check=check, timeout=30)
enddate = enddateinput.content
await message.channel.send('Please type in the Endtime (HH:MM):')
endtimeinput = await client.wait_for('message', check=check, timeout=30)
endtime = endtimeinput.content
# *********************************************
# I dont know how to check the time with the subfunction time_check :(
# The optimal result is the function wait at this point until datetime.now(now) = enddate & endtime.
# and then i want the function to continue working.
# *********************************************
await message.channel.send('Enddate & Endtime reached.')
await message.channel.send('Go on with the rest of the code :).')
async def time_check():
await client.wait_until_ready()
while not client.is_closed():
nowdate = datetime.strftime(datetime.now(), '%d.%m.%y')
nowtime = datetime.strftime(datetime.now(), '%H:%M')
if (nowdate == enddate) and (nowtime == endtime):
await asyncio.sleep(1)
# *********************************************
# BACK TO FUNKTION
# *********************************************
else:
await asyncio.sleep(60)
client.run(TOKEN)
The problem is, i need time_check() only to check every minute the current time with endtime/enddate.
If the endtime and enddate reached, time_check() can stop working and go back to on_message() to continue working the funktion.
I absolutely don't know how to integrate this check_time () function.
I hope someone of you can help me.
Thank you guys.
These are the functions you need to change, instead of checking every minute to see if the end time is reached I simply calculated the total seconds it will take to wait from the current time to the end time. I also added a check to see if the end time is in the past which is very important. In general I believe this is the best way to implement youre desired outcome.
#client.event
async def on_message(message):
def check(m):
return m.channel == message.channel and m.author != client.user
if message.author == client.user:
return
if message.content.startswith("!start"):
# Get end date.
await message.channel.send("Please type in the Enddate (DD.MM.YYYY):")
enddateinput = await client.wait_for("message", check=check, timeout=30)
enddate = enddateinput.content
# Get end time.
await message.channel.send("Please type in the Endtime (HH:MM):")
endtimeinput = await client.wait_for("message", check=check, timeout=30)
endtime = endtimeinput.content
# Get the two datetime objects, current and endtime.
endtime_obj = datetime.datetime.strptime(
".".join([enddate, endtime]), "%d.%m.%Y.%H:%M"
)
currtime_obj = datetime.datetime.now()
if not (endtime_obj > currtime_obj): # Check if end time is in the past.
await message.channel.send("End time can not be in the past!")
# Send the seconds to wait into the time check function
time_to_wait = endtime_obj - currtime_obj # The time delta (difference).
await time_check(message, time_to_wait.total_seconds())
async def time_check(message_obj, secs_to_wait: float):
await client.wait_until_ready()
await asyncio.sleep(secs_to_wait)
await message_obj.channel.send("Enddate & Endtime reached.")
await message_obj.channel.send("Go on with the rest of the code :).")
I am making a discord bot using discord.py. I want to make a command to purge all messages inside a channel every 100 seconds. Here is my code:
autodeletetime = -100
autodeletelasttime = 1
#client.command()
#commands.has_permissions(manage_messages=True)
async def autodelete(ctx):
global autodeleterunning
if autodeleterunning == False:
autodeleterunning = True
asgas = True
while asgas:
message = await ctx.send(f'All messages gonna be deleted in 100 seconds')
await message.pin()
for c in range(autodeletetime,autodeletelasttime):
okfe = abs(c)
await message.edit(content=f"All messages gonna be deleted in {okfe} seconds" )
await asyncio.sleep(1)
if c == 0:
await ctx.channel.purge(limit=9999999999999999999999999999999999999999999999999999999999999999999)
await time.sleep(1)
autodeleterunning = False
else:
await ctx.send(f'The autodelete command is already running in this server')
I want the loop to restart every 100 seconds after the purge is complete.
You should use tasks instead of commands for these kind of commands.
import discord
from discord.ext import commands, tasks
import asyncio
#tasks.loop(seconds=100)
async def autopurge(channel):
message = await channel.send(f'All messages gonna be deleted in 100 seconds')
await message.pin()
try:
await channel.purge(limit=1000)
except:
await channel.send("I could not purge messages!")
#client.group(invoke_without_command=True)
#commands.has_permissions(manage_messages=True)
async def autopurge(ctx):
await ctx.send("Please use `autopurge start` to start the loop.")
# Start the loop
#autopurge.command()
async def start(ctx):
task = autopurge.get_task()
if task and not task.done():
await ctx.send("Already running")
return
autopurge.start(ctx.channel)
# Stop the loop
#autopurge.command()
async def stop(ctx):
task = autopurge.get_task()
if task and not task.done():
autopurge.stop()
return
await ctx.send("Loop was not running")