Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I made this command called p!poll [message] where I want my bot to send an embed with [message] for the description and react with the emojis 👍 and 👎. The command, however, isn't responding and I don't understand why.
#client.command
async def poll(ctx, *, message):
embedVar = discord.Embed(title='Poll', description=f'{message}')
msg = await ctx.channel.send(embed=embedVar)
await msg.add_reaction('👍')
await msg.add_reaction('👎')
Your command is forgetting to call the command, which is the double parenthesis, ()
Simply can be fixed by adding: client.command() to the top where it previously says without the parenthesis
It's better to include "None" in your message decorator, as it allows members to know they must pass a message through, otherwise it would not run the command.
I choose to optionally add some more functionality to your command, (only if you wish for use) and the option of sending it to a different channel, but I have tried this and should work. Hope this helps, change it to whatever you need.
#client.command()
async def poll(ctx, *, message=None):
if message == None:
await ctx.send(f'Cannot create a poll with no message!')
return
questions = [
f"Which channel should your poll be sent to?"
]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('message', timeout=30.0, check=check)
except asyncio.TimeoutError:
await ctx.send("Setup timed out, please be quicker next time!")
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(
f"You didn't mention a channel properly, please format like {ctx.channel.mention} next time."
)
return
channel = client.get_channel(c_id)
embed = discord.Embed(title="Poll", description='{message}', colour=discord.Color.black())
message = await channel.send(embed=embed )
await message.add_reaction('👍')
await message.add_reaction('👎')
Related
This question already has answers here:
How to make discord.py bot delete its own message after some time?
(3 answers)
Closed 9 months ago.
Trying to get the bot to clear message after waited time but i can't seem to figure out why.
It waits but then doesn't clear the bots message, i think I've got the wrong variable but I'm not sure what it is.
#client.command()
#commands.has_permissions(administrator = True)
async def clear(ctx, amount = 5):
await ctx.channel.purge(limit=amount + 1)
await ctx.send("Cleared " + str(amount) + " messages")
time.sleep(2.5)
await ctx.message.delete()
Your command should be like this. Use asyncio library
await ctx.channel.purge(limit=amount+1)
await asyncio.sleep(your_time)
await ctx.send("Done 👌", hidden=True)
You'd wanna use something like this. It's a basic clear command.
#client.command()
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amout : int):
await ctx.channel.purge(limit=amout)
I want to wait for a private message that was sent only by the member. I am trying to use the check parameter for the client.wait_for() method but I can not seem to get it. I tried putting the check as the response.author but will not work since I just assigned response. Also I am executing this when a member joins using on_member_join which takes in a member argument (like this async def on_member_join(member). Anyone know how to properly do this? Any answers would be greatly appreciated!
Here is the code for this:
await member.send('What is your student number? ')
response = await client.wait_for('message')
student_number = response.content
When adding a check function to wait_for, that check function will get the received message as an argument. This means that it will check every single message the bot gets, pass all of them to your check function, and wait until one of them makes the check return True.
#client.event()
async def on_member_join(member):
def check(message):
return message.author.id == member.id and message.guild is None
await member.send('What is your student number?')
response = await client.wait_for('message', check=check)
student_number = response.content
Note how my example also makes sure the guild is None, as you explicitly mentioned waiting for a private message.
hi i am trying to make a discord.py bot so i can have a gif chat channel but when someone types a message in that channel then my bot starts repeating his message, pls help if u know.
my code:
#client.event
async def on_message(message):
with open("gif_chater.json", "r+") as file:
data=json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
if not message.content.startswith("https://tenor.com/") and not message.author.id == "760083241133932544":
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
exit
The on_message event
The issue is that the bot is constantly responding to itself, and it's because the on_message event triggers not just when users send a message but also when the bot sends a message. As such, once it tells the user that they must only post tenor gifs, it reacts to its own message and goes into an infinite loop, posting and deleting its responses.
Preventing the bot from responding to itself
To prevent the bot from responding to it's own messages, you should add a check at the start of the event like in the discord.py docs:
#client.event
async def on_message(message):
if message.author == client.user:
return
...
Also, the ID check at the end
The last condition in your code before it decides to send a message is checking the ID of the messenger (not message.author.id == "760083241133932544"). I don't know whether it's meant to avoid deleting you or the bot's messages but regardless, the check itself is bugged. message.author.id returns an integer but is then being compared to a string, and due to the conflicting types, will always return False.
To fix it, change your ID to an integer by removing the quotes: not message.author.id == 760083241133932544. As well, you should use the not-equals operator != instead of not to improve readability: message.author.id != 760083241133932544.
Also, since you already checked if the message starts with the website link, you can use an elif statement instead of rechecking the condition, since else/elif guarantees that the previous condition was false (aka, that the message didn't start with the website link):
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
Fixes combined
With the new changes, your function could look something like this:
#client.event
async def on_message(message):
# Don't respond to the bot's own messages
if message.author == client.user:
return
with open("gif_chater.json") as file:
data = json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've recently created a bot with the default kick and ban commands along with some other things. However, one thing I've really want to add is music commands. For example, .play <song name> would a the selected song. and .pause and .stop would pause and stop the music playing. Any tips or links to videos would really be appreciated. Thank you in advance.
Here you go. Unfortunately, I don't know how to make a song stop or pause, but if I will find out how to do it I will edit this answer.
import discord
import os
import youtube_dl
import asyncio
from discord.ext import commands
TOKEN = 1234567890 #change this to your token
client = commands.Bot(command_prefix = ".") #Here you can change prefix for commands
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
def endSong(guild, path):
os.remove(path)
#client.command(pass_context=True)
async def play(ctx, url):
if not ctx.message.author.voice:
await ctx.send('You are not connected to a voice channel') #message when you are not connected to any voice channel
return
else:
channel = ctx.message.author.voice.channel
voice_client = await channel.connect()
guild = ctx.message.guild
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
file = ydl.extract_info(url, download=True)
path = str(file['title']) + "-" + str(file['id'] + ".mp3")
voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
await ctx.send(f'**Music: **{url}') #sends info about song playing right now
client.run(TOKEN)
Optional, useful function
If you want you can make your bot leave the voice channel after the song/music stop playing. Add this at the end of your code, but before client.run(TOKEN)!
while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
How to use it
.play url - plays song from url (example .play https://www.youtube.com/watch?v=dQw4w9WgXcQ)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So basically when i run a command, the bot spams its response.
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]){
case 'embed':
const embed = new Discord.RichEmbed()
.setTitle('User Information')
.addField('Player Name', message.author.username)
.addField('Version', version)
.addField('Current Server', message.guild.name)
.setThumbnail(message.author.avatarURL)
.setFooter('Made By NotBanEvading')
message.channel.sendEmbed(embed);
break;
}
})
https://gyazo.com/a1c71fc097e1253bc036d1ef293f034e
bot.on('message', message =>.. means an event when the bot receives any messages.
Which means it will trigger when it recieves message from itself or other bots.
You can check if the message's author is a bot using message.author.bot, like so:
bot.on('message', message => {
// Do nothing if the message is from a bot.
if (message.author.bot) { return; }
let args = message.content.substring(PREFIX.length).split(" ");
// ... Rest of your codes
(P.S please make your title clearer on what you are actually asking. Rather than stating that you need help.)