#discord-bots
1 messages · Page 113 of 1
does the bot have permission to read messages where you were sending the message?
yes admin perms
what do you mean?
in the member list
anyoen know how to fix this?
2022-10-23 20:22:34 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
do pip list
in the terminal, and can you screenshot that?
Yeah
ignore the random stuff i accidently installed requirements from a different folder
okay do
you need to enable the .message_content intent before you pass it to your bot constructor
e.g. ```py
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)```
did that already
maybe same problem like me
nah the logger message would imply that it went online
so why doesnt mine work?
can you show the code for your intents and the bot constructor?
from discord.ext import commands
import random
import os
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix='.', intents=intents)
token = "my token is here usually"
@client.event
async def on_ready():
print("online")
client.run(token)```
thats all i have
2022-10-23 20:28:12 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected
and thats the error i get
i tested your code with 1.7.3 and didnt have any problem with it
you only set the members intent, not message_content
how do i do that?
^
Hmmmm weird
let me install it again
the error says that the variable filename wasnt defined before it tried replying to the message
@hushed galleonerror is gone but ima test if it works
do you have any clue why its not working for me?
hm, does the message content intent in the dev portal apply retroactively for older gateway versions?
Well, how do I fix it?
@hushed galleonworks tysm
this is more of a normal python question, you should open a help channel and paste your on_message code along with that error message and someone can help you there
#❓|how-to-get-help
@silent ridge well lets assume this does, do you have the Message Content Intent enabled in the developer portal?
That was the issue
it worked, really appreciated. Thanks for the help buddy!
Not yet i was thinking about it, but I was unsure if it was the best solution
and if it failed, I was unsure, how to replace message with interaction.followup and then doing it from there
you have a prefix set and ur not using it. use InteractionBot or enable message_content
how do i enable message_cotent
nvm thats the old code i fixed it now
ahhh okay.
Hi Guys!
I'm having an issue with discord embeds and using pages
The issue i'm getting is, it just adds the info from the second page onto the first page, it doesn't clear the first page first
pages = []
n = 4
new_main_Values_list = [temp_embed_values_list[i * n:(i + 1) * n] for i in range((len(temp_embed_values_list) + n - 1) // n)]
for itemy in new_main_Values_list: #main list loop
for item in itemy: #sub lists loop
C +=item
page = discord.Embed(title='Page 1/3', description='Description', colour=col)
page.add_field(name=None, value=C)
pages.append(page)
print("4")
message = await ctx.send(embed=pages[0])
await message.add_reaction('⏮')
await message.add_reaction('◀')
await message.add_reaction('▶')
await message.add_reaction('⏭')
def check1(reaction, user):
return user == ctx.author
i = 0
reaction = None
print("5")
while True:
if str(reaction) == '⏮':
i = 0
await message.edit(embed=pages[i])
elif str(reaction) == '◀':
if i > 0:
i -= 1
await message.edit(embed=pages[i])
elif str(reaction) == '▶':
if i < 2:
i += 1
await message.edit(embed=pages[i])
elif str(reaction) == '⏭':
i = len(itemy)
await message.edit(embed=pages[i])
print("6")
try:
reaction, user = await bot.wait_for('reaction_add', timeout=100.0, check=check1)
await message.remove_reaction(reaction, user)
print("7")
except:
print("Breaking 1234")
break
await message.clear_reactions()
this is the bit of code that's giving the issue
Can anyone explain why my custom .help command isnt working this is the code.
@client.command(pass_context=True)
async def help(ctx):
author = ctx.message.author
embed = discord.Embed(
colour = discord.Colour.orange()
)
embed.set_author(name='Help')
embed.add_field(name='.ping', value='Shows Bot Delay', inline=False)
await client.send_message(author, embed=embed)```
what's the error you get
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'send_message'
send_message doesnt exist in the recent versions of dpy
so what is the new way?
await ctx.send(embed = embed)
for DMing, you'd use .send() on the author object directly
its a help command for a discord server though
so its like .help and it shows the commands
oh, i thought you actually wanted to send to the author given your usage of it
ctx.send() sends to the channel the command was invoked from like blue's example
er, no
await ctx.send(author, embed=embed)
author shouldnt be provided in this case
oH
otherwise it would become the content of the message
Sorry to tag you, would you be able to help me afterwards?
^
can you show screenshots of what occurred?
sure
So this is the command displaying, and it looks fine
then when I press to go to the next page
I get this
and then if I press a third time, it gives embed size error, because they are limited to 1024 iirc
I think somethings wrong with the embed, like it's not giving separate ones for different pages
hm, assuming C is a string, it doesnt seem you're resetting it across each page, meaning it accumulates across each page
also the title is statically set to 'Page 1/3', so you wont see that updating
ah ok
can I make C global and then reset it before I print("4") ?
why would you need C to be global?
if its only used in the page embed you can simply redefine it after each iteration of your main list
ahh thank you
u dont have setup function inside that cog
That worked perfectly! Thank you so much!
does dpy gh not have examples for cogs?
the documentation does but not the github
ahhhh
same for extensions, but unfortunately doesnt show extensions combined with cogs despite its frequent use case
yeeee thats what i was looking for for this guy
is there any specific reason that my bots status works perfectly on windows but when i transfer it to my pi it just doesnt work my windows python version is 3.10.5 and my raspberry pis python version is 3.9.2
wdym by "status"
so discord changed how do you add a bot to server now
you generate an invite link for the bot and have people click it
afaik nothing's changed
there's only the new Add to Server button on the bot's profile
if you want to include that feature you can enable it in the OAuth2 page on the dev portal
yeah i enabled requires oauth2 grant by mistake that was my issue
ah you meant your invite wasnt working
might be too demanding on bandwidth
are self bots that can do it legal?
self bots are against discord's guidelines, so you're out of luck
unless you're able to use another streaming service or make your own
How would I add cool-downs, timers and delays to commands?
-
Cool-downs as in: You can’t use this command again for another 10 minutes
-
Timers as in: This command will execute every time “Python” is mentioned for the next 30 seconds
-
Delays as in: After 40 seconds, this part of the command will run. But without using time.sleep cause I don’t want to pause the entire program
cooldowns are included with the commands extension, and delays are built into asyncio with asyncio.sleep(), but your timers idea would need to be done manually with a listener
Delays are pretty easy. Just use await asyncio.sleep(seconds)
Timers might be a little bit more effort, because you'll need to store some sort of state on what time the timer was started, and check if the current time is less than start time + the timer length
Gotcha, I remember someone telling me about that a while back… 
Commands Extension, I’ll have to read on
And Listeners? Am unfamiliar with the term
oh, you havent used the commands extension before?
Yea, I know the logic behind it, but… not knowledgeable enough to know how to actually do it
Got a db set up for it though
You can bind the start_time to your bot instance
And use something like a global check or just a plain old if statement
Maybe I have but I don’t know the term? Unsure
you should start from here and also check out some examples of using the extension
https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
Listeners "listen" to events. i.e on_message this gets triggered when a message is sent. which is where youll ideally start for your "Python" idea
Ooh, yea I know them, didn’t know the term was listeners
My bad
listeners are distinct from basic event handlers
Would it work if I used the timer lib and ran a while loop to continuously check if the timer has reached x time?
discord.Client supports event handlers with the @event decorator while commands.Bot adds a listen() decorator which you can have multiple of for the same event, unlike the event handler
I'm not aware of that library but I don't think there's a need to
It should be relatively simple logic if you handle it yourself
Also streaming piracy
Got it… I think
Store start_time = datetime.datetime.now() when something happens, then later check (datetime.datetime.now() - start_time).seconds > 1800, and start the next timer only if so
(1800 seconds is 30 minutes btw)
Looks like Extra homework tonight 
Ahhh, I’ll try that 
if the timer only lasts 30 seconds as originally asked, i would simplify it to a dictionary
or perhaps a set
then have the command add the channel ID to the set, sleep 30s, and remove the channel ID, that way your listener simply has to check if the channel ID is there to know that the command is active
Why not try all the solutions out?
Let’s see which one works best 
the same thing as the Listening to DM reports!
Define "doesn't work"
and where are you setting this
no errors or anything it just doesnt show up and im putting it in @stray tanglek.loop(minutes=1.0)
oops
are the paths different?
i didnt change anything
are u storing the game locally?
yea
can u show code how ur setting
Hey @torpid hare!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
ok
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i thought it couldve been the version of python i have installed on my raspberrypi 3.9.2 i tried upgrading it but it broke everything and i had to reinstall the os
Why is it in a task? Are you changing it
Why is there so much duplicate code 😭
idk much ab raspberrypi but is the OS not different?
@torpid hare if the name parameter in discord.Streaming is empty the bot will appear to do nothing without an error double check that its getting more then nothing
cause i couldnt think of a better way of doing it sorry
different then what
all of the strings its grabbing is a game name it cant be empty
if it was empty it isnt a game
Where are you starting the task? Do you know if it's even running
his issue is it works on his local host windows. doesnt work on raspberrypi
yeah and I'm trying to figure out to what extent it 'doesnt work'
well if its exactly the same code running on both windows and the pi and one works but the other doesnt thats the only difference is the data that you are importing
all i got
u tried pointing directly to the path?
the only time it did work was when i put in a a string like so await bot.change_presence(activity=discord.Streaming(name="Hello", url=my_twitch_url))
i would put print statements to see what the data variable is before setting the presence
the file?
mhm
yes it is
is it works with the hello then its 100% where you are pulling that data var from
then why is it consistently working on windows?
according to ur code its not
try to use the FULL path on ur rpi
alright
on windows its properly pulling the data on the pi its not
and also, do you have logging setup?
that worked
yup figured
Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using
Client/Bot.run. More about that in?tag defaultlogging.
It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging
but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.
please get the setup so you see your errora
i will do that, thanks
have the names in a dict like
games = {
1: "foo",
2: "bar"
...
}```
And get from the key
Or even just use a list and the index
All of the duplicate lines can all just be used once
There's no reason they need to be in the if (or for you to have ifs at all)
Your 400 lines could be like 10
hi
that does make more sense
@client.command()
async def geninv(ctx, channel: discord.TextChannel = None):
user = ctx.author
await ctx.message.delete()
if channel is None:
invitelink = await ctx.channel.create_invite(max_uses=300,unique=True)
await user.send(f"invite in {ctx.channel.guild}!\n{invitelink}")
else:
invitelink = await channel.create_invite(max_uses=300,unique=True)
await user.send(f"invite in {ctx.channel.guild} invite goes to {channel}!\n{invitelink}")
I have this and it works fine but how can I make it so I can do $geninv id
instead of $geninv #channel
ive already tried but i get multiple errors
@swift trenchassuming you are using bot instead of client that should convert a id to a text channel whats the error?
Do you have the kick/ban order to give me, please, but let it go smoothly???
@chilly dove im not changing that anymore but can you help me with
@client.command()
async def channels(ctx):
channel = list(ctx.guild.channels)
c = str(channel)
em = discord.Embed(title='ALL CHANNELS/CATEGORYS', description=f"channels\n{c}")
await ctx.send(embed=em)
and make it return a list
@swift trench
Do you have the kick/ban order to give me, please, but let it go smoothly???
if you are trying to make it return a list of the names then you would have to loop through the the channels and append the names to a list
ctx.guild.channels is already a list
list comprehension would be much better in this case
ill try but I dont know a lot
@client.command()
async def channels(ctx):
channel = ctx.guild.channels
for c in channel:
c.append(channel)
em = discord.Embed(title='ALL CHANNELS/CATEGORYS', description=f"channels\n{channel}")
await ctx.send(embed=em)
@chilly dove
i tried this
c is not defined, or rather you are trying to use append on something that is not a list
try this py channel_names = [channel.name for channel in ctx.guild.channels]
the guild instance has .text_channels which will only return text channels and not all channels
@chilly dove
what if I wanted it to return like
1
2
3
4
or maybe
1 text
2 category
3 voice
4 category
well you can check if something is one of those by using something like py isinstance(channel, discord.TextChannel) and substitute any of these:
TextChannel
VoiceChannel
CategoryChannel
StageChannel
ForumChannel
for text channel
i wanna ask something that on message event and client .command are not responding together
huh
if i remember correctly overriding the on_message event causes the bot to not process the command
so can it be fixed?
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=process#discord.ext.commands.Bot.process_commands you gotta use this at the end of the event
or just change@bot.event to @bot.listen()
I also have a question where do I put the commands in main.py?
I'm new to bots
I also have a question where do I put the commands in main.py?
usually we use Cogs when developing a big bot which has many commands
worked ,,, thanks
do you have an order to say? so that I write, I say and the bot says
"Order to say" what
Basically the user says !repeat heeeeh GA we
🫦🦶
Bot replies heeeh GA we
What the
erm is this even a thing 💀
good luck querying it
How to use slash subcommands in cogs? (disnake)
can u recommend me some tutorial about connecting discord bot to online database
Then I will ask
"how do I use a json file as a database"
Can't say I know of any, I'm sure there's plenty of tutorials out there for using sqlite and other things
erm ok
Couple months ago I helped develop an AI chat bot that utilized OpenAI's GPT-3 and implemented it into discord. So far it's doing pretty well
Nice
But the credits offered are hella limited, I also tried
Credits?
Yea, when I tried it, it was still in Closed Beta and u were offered a limited amount of credits, which are used to generate responses. Once those are finished, u gotta buy them to keep using the AI
I think I know what you're talking about. The only thing I regularly pay for are the servers to upkeep the bot so I'm not sure if that's still a thing
Would you be interested in trying out the bot though?
is it on_guild_channel_add or on_guild_channel_create ?
does anyone know why after 3/4 minutes my bot doesn’t verify anymore?
my bot is still running (online status) so I don’t understand it
The latter
Is there a way to get invited users through an invite link?
Who joined using that url?
maybe you can get the invite url that was used when a new user joins your server
if not you could save invites and how many times they were used and when a user joins check which invite has been updated
File "main.py", line 2, in <module>
from discord import app_commands
File "/home/runner/pythondisc/venv/lib/python3.8/site-packages/discord/app_commands/__init__.py", line 12, in <module>
from .commands import *
File "/home/runner/pythondisc/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (/home/runner/pythondisc/venv/lib/python3.8/site-packages/discord/enums.py)
why does this happen when i import app_commands from discord
Are you using the latest discord.py version?
import commands from discord.ext instead this ! i think
ill try it
i think app_commands is for slash commands
yes
idk if its the same thing
Traceback (most recent call last):
File "/home/supremium/Python/main.py", line 3, in <module>
from discord.ext import Option
ImportError: cannot import name 'Option' from 'discord.ext' (unknown location)
yeah its probably app_commands
@sick birch I just thought about it. Could I maybe access the buffer where all the bot's execution orders are stored and remove certain ones?
how i manage cooldowns replies for individual commands in cogs?
Either in the Cog per command error handler and catch the cooldown error or check the command in the main error handler.
can anyone rate my code's optimization ? I'm a noob and am looking towards writing nice code because I'm working on a very big project
variable names are in french so a french developer would understand way better
I recommend coding in English.
that's a totally valid recommendation but since I started in french I'm a bit lazy to change everything to english
but you're right it's helpful in these kind of situations where I'm sharing code with foreigners
When asking for help it's easier, the library is already English so now it's a mix of. Other than that I recommend typehinting.
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Other than that I can't really recommend anything else since I have no clue what this does.
Maybe space your code a little bit, leave like a line after a block of code
if ...:
# ...
else:
# ...
# rest of the code ...
okay will do
yeah understandable, it would be pretty long and annoying to explain tho
Can someone help?
Is there a on_channel_delete event or something like that?
is there a way to make a discord bot start my aternos minecraft server by use of a command?
!d discord.on_guild_channel_delete
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
ty
Likely not, since people would abuse that to unnecessarily keep servers online
Not by a module, but they can always scrape the website
!pypi python-aternos
@fallow mauve
That definitely violates aternos tos
what if i didnt use it against tos?
bcs i just need a way for my members to run my server when they wanna get on
i wouldnt be abusing it or anything
but idk if that would matter
Please stop pinging random people
in on_member_join
embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to sever {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'``` how can I fix?
I think it's just datetime.utcfromtimestamp
You already have from datetime import datetime
Still violates ToS regardless of what you do with it
Plus your bot is going to need a VPS anyway so just run your Minecraft server on it
2 in 1
so just py timestamp=datetime.datetime.utcfromtimestamp()) ?
timestamp = datetime.utcfromtimestamp()
bscly on import
wouldn't member.avatar.icon.url work?
or should i do display_avatar
Oh yea it works its cuz a user didn't have a avatar, is it possible to make it ignore that error and just show no avatar or smth?
member.display_avatar.url
it should display the default avatar aswell
ah ok
ok thx anyway
code
i fixed it , i forget to enable the intents
Where can I host my discord bot?
See pins of #965291480992321536
thanks!
@bot.listen()
async def on_message(ctx):
if any(x in ctx.content.lower() for x in [".cumpara"]):
log_data = load_stats()
authorid = str(ctx.author.id)
author = str(ctx.author)
if authorid {'cumpara'} in log_data:
log_data[str(ctx.author.id)]['cumpara'] += 1
save_stats(log_data)
else:
log_data[str(ctx.author.id)] = {}
log_data[str(ctx.author.id)]['cumpara'] = 1
save_stats(log_data)
if any(x in ctx.content.lower() for x in [".anuleaza"]):
log_data = load_stats()
authorid = str(ctx.author.id)
author = str(ctx.author)
if authorid {'anuleaza'} in log_data:
log_data[str(ctx.author.id)]['anuleaza'] += 1
save_stats(log_data)
else:
log_data[str(ctx.author.id)] = {}
log_data[str(ctx.author.id)]['anuleaza'] = 1
save_stats(log_data)
if authorid {'anuleaza'} in log_data:
code isnt working bcs this line
any idea whats wrong with it?
If ctx.author.id == your_id:
what happens here
Idk what your trying to achieve
in trying to jsonify how many times an user type the command using a listener
it has to log something like
{
id: "userid",
anulat/cumparat: how much times
}
hey
why does it say "undefined name "commands""
when i put @lavish micamands.has_permissions(kick_members=True)
From discord.ext import commands
Idk not sure
i have that imported
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import *
class aclient(discord.Client):
def init(self):
super().init(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = 1020363390272671805))
self.synced = True
print("We have logged in as {self.user}.")
client = aclient(intents=discord.Intents.default())
tree = app_commands.CommandTree(client)
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if reason==None:
reason=" no reason provided"
await ctx.guild.kick(member)
await ctx.send(f'User {member.mention} has been kicked for {reason}')```
from discord.ext.commands import has_permissions, MissingPermissions?
nope :/
says no attribute called command
@has_permissions ?
Remove commands.
How to host bot 24*7 free pls helppoo
Also ping if reply plis :)
uh
🗿
u can't host reliably for free prob
free host is not trusted
Like they gonna take over my bot and destroy servers or smthn?
Like they can?
I mean it's only me who uses the bot...👀
To like remind me to do stuff bcz im one forgetful little bitch
So i dont really need anything fancy unless the bot like goes offline every other day
Its not even in any server so atmost it'll just sabotage my dms or that one server we all have where we write random stuff like grocery lists and all
So i dont wanna spend moneh u feel me ¯_(ツ)_/¯
its 5$/month
So just run the bot when you need it
Does it need to be online all the time?
Yes
I mean like how else is it supposed to remind me to do stuff if i need to remember to turn it on to remind me ||duh🗿||
Google Calendar is free if we see like that🥲
Just get a raspberry as an one time investment 
Waht i just want someone to ping me why must that be so hectic lol😔
I don't earn atm legit living off my father's money so i cant spend on, well, anything at all tbh...🗿
Same as before
If i remember correctly it wasn't implemented before
I mean in the version that supports slash commands
Ohhh
Thought you meant prefix commands error handling
I think for the majority of the part it's the same
Is there any example?
it is if u are using the run method if u are using start method u have to setup ur own logger or use discord.utils.setup_logging iirc
Sorry, I have no plans on helping here as people have personal problems for unknown reasons and do not believe I help anyone or contribute to anything. They also go on and insult you in your back for no reasons, and I'd rather not have to interact with such type of people or see them while "helping" (apparently I don't) others.
Hence I won't help anymore, so that these people are happy.
how do i make this so it uses the AI framework?
import discord
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
conversation = {
"what is": "I don't know, I'm just a bot!",
"think": "I don't think, I just do",
"wtf": "Good question",
"you had it": "Somebody must have swiped it! Is there another one?",
"like": "I love lamp",
"crickets": "It's pretty quiet in here",
"yes": "That's amazing",
"ping": "PONG!",
"when": "Maybe a little later. I don't know yet. I'm kinda busy here",
"who are you": "I'm a bot!",
"load a bowl": "I'm down! Where's the lighter?",
"you got some bud": "I thought you did!",
"is it 4:20": "It's always 4:20 somewhere!",
"how can we": "If I knew that we wouldn't be asking",
"sup": "Chillin'",
"what's up": "What is?",
"that's smart": "I try my best",
"sus": "I didn't do it. Nobody saw me do it. You can't prove anything!",
"where": "Somewhere",
"morning": "Good Morning!",
"gm": "gm",
"no way" : "I doubt it",
"yes" : "I believe so",
"wake and bake": "I'm down. load it up!",
"smoke": "I got five on it!",
"kind of bud": "the sticky icky son!",
"how are you": "excellent, how are you?"
}
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.channel.id != 1018756543816155187:
return
#loops through the "conversation" dictionary to check if the keywords are used and if so responds accordingly
for word, answer in conversation.items():
if word in message.content.lower():
await message.channel.send(answer.lower())
#offers help when the word "help" is entered
if 'help' in message.content.lower():
await message.channel.send("Try saying 'hello'")
i want to use the neuralintents module
It's fine, hopefully you'll get the help needed from others. If you don't I'll eventually help again though I doubt for the reasons above

how can I turn this  into :gimmetail: ? I'm trying to set a variable of it.
i tried emoji.demojize(variable) and emoji.emojize(variable, language='alias') and niether seem to work :/
nvm, I just ended up using regular expression to filter it out lol
anyone know why it won't mention the user and why it displays that at the start?
for the first one, you're probably not using the mention property. For the second one, you're passing an interaction object for whatever reason
result[0] apparently is a tuple
read the error :)
alright i fixed the mention but can't figure out the other
no? that's the exact same thing as int(result[0]) and will throw the same exception. int returns an integer, as in a number, not a string. You should check why result[0] is a tuple instead of whatever you want it to be, or maybe you forgot that result is a nested tuple
i may be wrong, but i think where you have
if result is None
maybe do
if result = None
cause that's what i use
you're probably doing something like
await interaction.response.send_message(f"{interaction} ...")
i don't see one..
import discord
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
class aclient(discord.Client):
def init(self):
super().init(intents=discord.Intents.default())
self.synced = False
async def on_ready():
print("We have logged in as {self.user}.")
Intents = discord.Intents(messages=True, guilds=True)
client = discord.Client(intents=Intents)
tree = app_commands.CommandTree(client)
@tree.command(name="ban")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason: str):
if reason==None:
reason=" no reason provided"
await ctx.channel.send(f"{ctx} <@!{member.id}> got banned for {reason}")
await ctx.guild.ban(member)
client.run("token")```
await ctx.channel.send(f"{ctx} <@!{member.id}> got banned for {reason}")
i don't see an error with this, maybe i'm being stupid lol
What I wanted to make: When someone type those things on chat or dm he has to add +1 to 2 diff categories (if .cumpara has to add +1 to cumpara and the same thing for .anuleaza) but I'm getting errors trying to store info (also it has to autogenerate if theres nothing)
Code
@bot.listen()
async def on_message(ctx):
if any(x in ctx.content.lower() for x in [".cumpara"]):
log_data = load_stats()
authorid = str(ctx.author.id)
author = str(ctx.author)
if authorid in log_data["cumpara"]:
log_data[str(ctx.author.id)]['cumpara'] += 1
save_stats(log_data)
else:
log_data[str(ctx.author.id)] = {}
log_data[str(ctx.author.id)]['cumpara'] = 1
save_stats(log_data)
if any(x in ctx.content.lower() for x in [".anuleaza"]):
log_data = load_stats()
authorid = str(ctx.author.id)
author = str(ctx.author)
if authorid in log_data["anuleaza"]:
log_data[str(ctx.author.id)]['anuleaza'] += 1
save_stats(log_data)
else:
log_data[str(ctx.author.id)] = {}
log_data[str(ctx.author.id)]['anuleaza'] = 1
save_stats(log_data)
Error
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
why are you subclassing client and not using that class at all?
take a look at the first bit of the string and see if you spot something off
what does ctx mean?
i literally began discord bots today sry
don't use JSON as a database
context ig
why notttttt.. is just about 4 users
oh okay ty
a database will just make it more complicated at that point fr
you sure it printed absolutely nothing? did it print some empty parenthesis ()?
with a database, issues like these don't tend to happen. Either way, if you really want to know, your JSON file is probably not formatted correctly
no
ohh i see my mistake
it's the {ctx} in the formatted string causing the weird message
you should print it before trying to get the role, not after, otherwise you're gonna get an error and the print statement won't get executed
thanks guys :)
correct
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 209, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\information\cog.py", line 192, in userinfo
e_view.from_message(interaction.message, timeout=None)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 260, in from_message
for component in _walk_all_components(message.components):
AttributeError: 'NoneType' object has no attribute 'components'```
button = nextcord.ui.Button(label="Show all Roles", style=nextcord.ButtonStyle.blurple)
e_view = nextcord.ui.View(timeout=None)
e_view.from_message(interaction.message, timeout=None)
async def button_callback(interaction):
embed_roles = nextcord.Embed(title="Roles", description="\n".join(reversed([f'> {r.mention}' for r in filter(lambda role: not role.is_default(), member.roles)])))
button.disabled = True
button.style = nextcord.ButtonStyle.grey
await interaction.edit_original_message(embeds=[userinfo, embed_roles], view=e_view(interaction.message, timeout=None))
async def button_timeout(interaction):
button.disabled = True
button.style = nextcord.ButtonStyle.grey
await interaction.edit_original_message(view=e_view)
button.callback = button_callback
button.timeout = button_timeout
view = nextcord.ui.View()
view.add_item(button)
consider sqlite/postsgres. But yeah, pymongo would do I guess, though I'd look for an async driver if I were you
im hosting a server with mariadb but i dont wanna waste time making it remote just for that idiot bot
at that point ill just giveup with that ig
from_message is a classmethod, you've got no reason to do that if you're already instantiating a new view class
that's a tuple with an integer inside of it
um, ok? what's your point?
is just using 5sim api trying to make an account for multiple persons and log their activity
thru api
well, I'm assuming you know what a tuple is, so I don't think you really need my help
What you mean?
so, what's your issue now?
why are you calling View.from_message?
i cant log their activity
Because i want to edit the Button after it is pressed
how do i turn my ban message into an embed then?
i mean i can manually but im losing time at that point fr
correct, and you can access the contents inside the tuple how?
you probably want an integer instead of a string
that's not how you do it. You have to pass in the current instance of the class as your new view when you edit the message
And how?
!d discord.abc.Messageable.send (checkout the embed kwarg). Fwiw you should try not making ban commands, Discord already does this, so there's really no point. Anywho, if you want your message to be an embed, you need to pass an Embed object to the embed kwarg in whatever method you're using the reply
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
no, result[0] returns a tuple, you gotta index the tuple returned by result[0]
i am just practicing with ban command
set view to self when you edit your message? cause self if your current instance
Yes, I had that at the beginning too, but it didn't work and then I was told that I should use from_message, that the view will only be defined later
how can i send message to a specified user?
Via dm?
hmm
where's the syntax error
embed = discord.Embed(title="Banned Successfully.", description="<@!{member.id}> got banned for {reason}", color=discord.Color.random())
ye
member.send
could you show your full code?
your description isn't an f-string
Is this Not enough what i send?
wdym?
still doesn't work somehow
If not do you have the paste command? @fading marlin
oh, wait, that's in a Button subclass isn't it?
what "doesn't work"?
@bot.listen()
async def on_message(ctx):
user = await ctx.get_user('852673731900735508')
if any(x in ctx.content.lower() for x in [".cumpara"]):
await user.send(ctx.author.id+" a cumparat un numar.")
if any(x in ctx.content.lower() for x in [".anuleaza"]):
await user.send(ctx.author.id+" a anulat un numar de telefon.")
File "D:\etc\devv\bilenatorul\main.py", line 258, in on_message
user = await ctx.get_user('852673731900735508')
AttributeError: 'Message' object has no attribute 'get_user
hell nah
bot.get_user or ctx.guild.get_member
also, get isn't a coroutine
The button is in the same class like the command
it says that the line is invalid syntax in the console
I am telling you how. Index the first item
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
could you send the traceback?
Only the command or the whole cog
the command should be just fine I guess
embed = discord.Embed(title="Banned Successfully.", description=f"<@!{member.id}> got banned for {reason}", color=discord.Color.random())
^
SyntaxError: invalid syntax
line above might be causing some issues?
@bot.listen()
async def on_message(ctx):
user = bot.get_user('852673731900735508')
if any(x in ctx.content.lower() for x in [".cumpara"]):
await user.send(ctx.author.id+" a cumparat un numar.")
if any(x in ctx.content.lower() for x in [".anuleaza"]):
await user.send(ctx.author.id+" a anulat un numar de telefon.")
tried adding/removing awaits still getting errors
TypeError: object NoneType can't be used in 'await' expression```
such as this one
!d discord.ext.commands.Bot.get_user id should be an integer, not a string
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
@commands.has_permissions(ban_members=True)
decorators can only be used to decorate functions or classes
oh, so my embed is just in the wrong place lol
i just put it anywhere i didn't know
it's in the middle of my ban member command 💀
it should be something like paste.pythondiscord.com/asdjfklajsdklf, that's just the url to the paste bin
@bot.listen()
async def on_message(ctx):
user = await bot.get_user(852673731900735508)
if any(x in ctx.content.lower() for x in [".cumpara"]):
await user.send(ctx.author.id+" a cumparat un numar.")
if any(x in ctx.content.lower() for x in [".anuleaza"]):
await user.send(ctx.author.id+" a anulat un numar de telefon.")```
user = await bot.get_user(852673731900735508)
TypeError: object User can't be used in 'await' expression
get_user isn't a coroutine
what do u mean
you can only await coroutines, get_user isn't one
the law requires me to say that you should report to Discord I guess
await user.send(ctx.author.id+" a anulat un numar de telefon.")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
code is upper..
this is basic python, you can't + an int and a string
javascript can do that..
Haha sry i pasted the wrong link
thanks
it'd be better if you'd just subclass ui.View instead of doing all of this mess
I know but subclass i also a mess xD
it'd be a lot simpler to accomplish what you're looking to do. If you need examples: https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
So you cant help me in this case
this just isn't a good implementation, that's all.
You're trying to call a class instance for some reason? (line 62). You should pass just e_view to your new view like you do in line 67. Also, you have to respond to interactions, so use interaction.response.edit_message instead of what you currently have
is there a way to make custom emojis bigger in embeds?
text-wise? no
what is that
description, field values (you can't have mentions/emojis anywhere else)
unless you use an image, no
hmm image, i don't know how it would work since i need to use multiple of them mixed with text
generate the text on top of an image and edit emoji sizes yeah, you'll have to stick with the size
that looks really neat
How should it looks l?
class Something(discord.ui.View):
Is it possible to make python send messages with your own account?
so no bot that does it with an command. But if you run your code it sends "hello" from your account for example
This is self botting and in violation of discord terms of service agreement and in regulation with rule 5 we will not provide assistance here
ah okay, was trying to make an AI respont for you on discord, whatsapp etc but didnt know it was against their terms of service
is it also against the terms to check the message you received in python?
help
Any sort of user account automation is considered self botting
Did you install discord.py?
Is the version you installed it on the same as the python version?
Perhaps try a venv to avoid confusion?
ah fuck, well thanks for saying it before I did something wrong haha
I am a beginner in Python
@sick birch
!venv
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Try creating a venv
is it against terms of service if My bot is designed to PM a user if/when they receive a warning in a server that they are in?
I assumed it wasn't, but just thought i'd find ut
You are allowed to do that
Nope. @unkempt canyon does this
ah cool
hey
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
class aclient(discord.Client):
def init(self):
super().init(intents=discord.Intents.default())
self.synced = False
async def on_ready():
print("We have logged in as {self.user}.")
Intents = discord.Intents(messages=True, guilds=True)
client = discord.Client(intents=Intents)
tree = app_commands.CommandTree(client)
@tree.command(name="ban")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason: str):
if reason==None:
reason=" no reason provided"
await ctx.channel.send(embed=embed)
await ctx.guild.ban(member)
embed = discord.Embed(title="Banned Successfully.", description=f"{member} got banned for s", color=discord.Color.random())
client.run("TOKEN")```
error
```Traceback (most recent call last):
File "main.py", line 26, in <module>
embed = discord.Embed(title="Banned Successfully.", description=f"{member} got banned for s", color=discord.Color.random())
NameError: name 'member' is not defined```
@fading marlin do u know why member is undefined
im supremium 😄
how would that affect it
intents?
that's basic python. You should pay attention to your indentations
this
a = "a"
b = "b"
if a == "a":
if b == "b":
print("a and b are the same")
is not the same as
if a == "a":
print("a is the same")
if b == "b":
print("b is the same")
#delete invite links
@bot.event
async def on_message(message):
if message.guild is None:
return
role =nextcord.utils.find(lambda r: r.name == 'Consigliere', message.guild.roles)
if role in message.author.roles:
return
discordInviteFilter = re.compile("(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
if discordInviteFilter.match(message.content):
await message.delete()
await bot.process_commands(message)
can someone help me with this error?
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kouxi\Runa\main.py", line 100, in on_message
if role in message.author.roles:
AttributeError: 'User' object has no attribute 'roles'
@commands.command()
@commands.has_permissions(manage_messages=True)
async def role(self, ctx, user: discord.Member, rank):
addrole = discord.utils.get(ctx.guild.roles, name=rank)
print(addrole)```How do I get the rank by them only typing the name of the rank in
message.author is a discord.User for some reason
If channel is a private channel or the user has the left the guild, then it is a User instead.
so i gotta change it to a public channel?
i dont get it tho
You need to use the command in a public channel, yes
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
class aclient(discord.Client):
def init(self):
super().init(intents=discord.Intents.default())
self.synced = False
async def on_ready():
print("We have logged in as {self.user}.")
Intents = discord.Intents(messages=True, guilds=True)
client = discord.Client(intents=Intents)
tree = app_commands.CommandTree(client)
@tree.command(name="ban")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason: str):
if reason==None:
reason=" no reason provided"
await ctx.channel.send(embed=embed)
await ctx.guild.ban(member)
embed = discord.Embed(title="Banned Successfully.", description=f"{member.id} got banned for {reason}", color=discord.Color.random())
client.run("token")```
how would that change the fact that member and reason is undefined
because of your scope
oh lol
thank u robin
wait, is there a way to change the code and bypass this so that it will take effect whether its public channel or not
you can check if message.author is an instance of discord.User using isinstance, if it's not, you can probably get roles attribute
no, not that scope, see https://realpython.com/python-scope-legb-rule/
You kinda can
There are a few reasons that it's a discord.User:
- Private channel in a guild
- User left
- Message is in a DM channel
You can only get .roles if it's in a private channel
maybe instead of checking if they have a role, i can check if they have admin permissions?
You could try something like:
try:
roles = message.author.roles
except:
# handle error here
because we care about looks > personality
agreed
class MyView(discord.ui.View):
def __init__(self):
super().__init__()
for i in range(25):
self.add_item(Button(label=f"{i}"))
how would i make a callback for each one of these buttons?
You would subclass button and each would have callback
how would i make the bot send a error whenever the wrong grouped sub command is provided
What is the easiest way to have a user specific cooldown
Can someone please help me with discord.py?
I'm trying to send a private message but it just displays the message in chat, not as a PM.
await ctx.send(user, embed=embed2)
here is my code
ctx.send() sends the message in the same place you use the command
so if you use the command in a guild channel it'll send in the same guild channel, if you use it in a DM it'll send in a DM
ah ok
how do I make it send as DM from wherever
await user.send(embed=embed2)
Figured it out 🙂
@little lava Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
haha, our bot found your invite link filter :p
you can just omit the link and put in a placeholder
import discord
from discord.ext import commands
client = commands.Bot()
@client.event
async def on_ready():
print("Bot serving contents!")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Spam Detector"))
@client.event
async def on_message(ctx):
if ctx.content.startswith("URL"): # Replace URL
await ctx.delete()
await ctx.channel.send(f"{ctx.author.mention} Please don't post invite links here!")
client.run("TOKEN")```
XD yes i want that
code seems ok but the bot not working with <Administrator> permission
more than likely missing perms to manage messages or send messages in that channel
I just tested few things and found that the bot cannot detect the URLs..
if ctx.content.startswith("https://"): # Here
im googling now, but did not found correct answer yet
bots most definitely can detect links
is there another method to detect the URL?
other than ctx.content.startswith ?
it seems only detect words.. not URL.
Use regex
That's a bit of complex topic, you need to take some tutorials
is it really possible to merge two json files without getting a brick?
I found some information about this and trying now!, thank you for the information!
For what
You can do it just by replacing last } in first file with , and removing the first { in second file, then merge them
Although with this method you might get duplicated keys
Or by loading them both and merging with dict.update
Not sure why'd you need to do it at all
my buttons stop working after a few minutes
even when the bot is online
anyone know why?
@wintry shoal
their not persistent
hello, how come this isnt working? @bot.command() async def convert(ctx, message): await ctx.send(f"{message}" / 125)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for /: 'str' and 'int'
because u are trying to divide and int and str
how would i fix it
learn python basics
thanks i really appreciate the help in the python help server
we are here to help not spoon feed code
this is also the discord bots help channel and ur issue lies within the basics of python not a didscord bot
i figured it out 🙄 @bot.command() async def convert(ctx, message): robux = message divide = 125 result = float(robux) / divide await ctx.send(result)
nah dude, i found the fix, it was the timeout
you cannot divide a string
yeah ik now lol, i figured it out
if you want to divide it should be a int not a string
There's a difference between help and spoon feed
.
you made it more complex lol
Yes, but since it's a simple error it tells me that you don't know basic python
wasnt really talking to you but ok go off
eh it works lol
🤓
it's never gonna help you learn if you keep coding like that lol
They will do everything but learn python
idc how complex it is as long is works
yes lol thats what makes a button persistent. timeout is None, and custom_id
🤦 ok
i don't think i really need a custom_id
yes you do?
So if a car drives but it crashes into a wall it doesn't matter since it works
how do you expect the lib to find the button lol
no way youre still talking
No way you still play fortnite
i haven't gotten any error without the custom_id
i'll add a custom id if i come upon a bug
Yes that's me talking to you since your a very uneducated user
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Here now this is how you learn python
you're*
Ok? Cool but that still doesn't prove my point of you not learning something and just copy and pasting
its not a bug and you won't get and error. the button will not work after restarting the bot.
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
ok now shut up, and go code
incase you didn't use your 2 eyes i clearly above said that i looked up how to fix it and fixed it
Yes but it shows me you don't know basic python so you need to learn python
Google won't get you a job bro 💀
i dont need a job
I'm crypto rich for life
ur a 12 year old on fortnite trolling. ima block u.
Cap your broke my guy
you're*
bro 💀
dude's mind forgot to add this to his search list var
well it seems ive won here, take your L
go play roblox
💀
you asking someone that you just insulted what a float is?
how ironic
Damn ur cat vaping
Bro i dont want to get banned, we should go to #ot0-psvm’s-eternal-disapproval
anyway
@slate swan mind telling me if you know what a float is? lmao
maybe if you told a potentially new coder what they were trying to do with the code instead of just "learn python basics"

for one this is a discord bot channel. not a python basics channel, two you shouldn't feed people code. three he started trolling the second I told him to learn python basics if you don't understand why you cant divide an INT and a STR
this also isn't the place for "new coders" you shouldn't be creating discord bots if you are a "new coder"
can you show your actual code logic.
from what u pasted its out of order
and confusing
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yea you are iterating through data and assigning values then you exit the for statement without adding the values to the embed so the last iteration is what is used
mmh
and how can I change that?
you need to add the embed fields in your first for statement
you are also duplicating code
you can just
embed.add_field(name=retailer['retailer']['retailler_name'], value=....)
and request are blocking. aiohttp would better suit you
u don't define it anywhere
Seems like come is a dict, not a list/tuple
there is no error but bot is not replying
its channel.send not channel.sent
Using dpy 2.0 and not getting any errors? This is on purpose, the library now uses logging to send errors but only if you're using
Client/Bot.run. More about that in?tag defaultlogging.
It's recommended to setup logging yourself if you aren't using .run or use the utils.setup_logging helper function: just put discord.utils.setup_logging() anywhere in your running file. Docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.setup_logging
but I can't use Client/Bot.run!
You can! You can load cogs and do other stuff in the newly added setup_hook method that is called once after the bot logs in, more about that and how to implement it in ?tag setuphook.
You should also be using an async lib for sqlite, such as asqlite or aiosqlite
yee
real helpful, mr "events team" member
it was because there was a typo in the word "attachments"
Bones doesnt know everything? They're just experienced and have there own life and things to do
staff also don't know how to spell
it would seem
took me 2 hours to see the typo
don't*
No? it should be "doesn't"?
Seems like you dont either but no one is critizing your writing, are we?
no, it's "don't"
"staff don't know everything" not "staff doesn't know everything"
Now i specified their name, now its correct, no?
it would be if it was "doesn't"
Either way lets not be pedantic and flood the chat
let's*
You forgot to correct my punctuation.
one thing at a time lad
Let's stop whatever this is
yes
omg the infamous brad09 has changed his pfp omg
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
HAHHAHAHAHA
Just in time for Halloween. Now please respect the channel topic. Thanks
why cursor = await cursor.execute(...)?
are you sure it returns the cursor? Or does it return the query status code
How would I subclass each button
async def whitelist(ctx, user: discord.Member=None):
File "D:\etc\devv\bilenatorul\main.py", line 45, in check_whitelist
if str(ctx.author.id) in f.read():
AttributeError: 'function' object has no attribute 'author'```
```py
def check_whitelist(ctx):
with open('users.txt') as f:
if str(ctx.author.id) in f.read():
return ctx.author.id
@bot.command()
@bot.check(check_whitelist)
async def whitelist(ctx, user: discord.Member=None):
if user == None:
await ctx.send("Ai uitat sa mentionezi persoana sau id-ul.")
return
def whitelisted(user_id):
with open('users.txt', 'r') as f:
if str(user_id) in f.read():
return True
else:
return False
def addwhitelist(user_id):
with open('users.txt', 'a') as f:
f.write(f"{str(user_id)}\n")
f.close()
if whitelisted(user.id) == True:
await ctx.send(f"{user} este deja in lista de useri.")
else:
addwhitelist(user.id)
await ctx.send(f"{user} a primit acces la comenzi.")
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Did you not understand the error 
Read the last line of the error
You're trying to convert that string to an int
Like doing int("abc") which makes no sense
get_channel needs a channel id
You need to figure out where you're storing that
Yes but where in the tuple
You're selecting msg, channelID
So your tuple will also be (msg, channelID)
Nonononon
Don't do that lmaoo
Go back to your old code
You already have the channel id
It's the second item in the tuple
So just use come[1] instead
In python you can access elements of a tuple and list with their index, starting from 0
!e ```py
data = ("message", 12345)
print(data[0])
print(data[1])
@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | message
002 | 12345
why i am getting this error? RuntimeError: Event loop is closed
Can you send the full traceback?
@vocal snow how to send full traceback?
Should be zero because you'll have one result
But if it's saying key error that means it has zero results for that guild and you need to make sure the channel ID is saved for that guild
If there are no results for that guild id itll return None
@slate swan Learn how to debug, even simple print(come) would work 😉
Well, it would be better if you check what your variable actually contains
I need a help
{'msg': '%member hello', 'channelID': 1013088096633499708} your variable clearly does not have 0 or 1 keys
Which discord version?
hello, has anyone got an example for slash commands with the new discord 2.0
it's 2.0.1
Can you share full traceback?
how can i send to you?
ctrl-c ctrl-v
will it be safe here?
no, you need to learn to use dictionaries
it's already a dict, why are you casting it to a dict
TOKEN =""
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_connect():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(TOKEN)
try py-cord extension?
import discord
# required py-cord extension by pip3 install py-cord
@client.slash_command(description="Test bot")
async def test(ctx): # Trigger
await ctx.respond("Hello World!")
It's your code, I need traceback of your exception
Traceback (most recent call last):
File "F:\discord bot\bot.py", line 32, in <module>
client.run(TOKEN)
File "F:\pyenv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "F:\pyenv\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "F:\pyenv\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "F:\pyenv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "F:\pyenv\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "F:\pyenv\lib\site-packages\discord\client.py", line 580, in login
data = await self.http.static_login(token)
File "F:\pyenv\lib\site-packages\discord\http.py", line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CE8B9E71F0>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
discord.errors.LoginFailure: Improper token has been passed.
Your token is not valid
Ok
Reset my token but it still showing me error ```
Traceback (most recent call last):
File "F:\discord bot\bot.py", line 32, in <module>
client.run(TOKEN)
File "F:\pyenv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "F:\pyenv\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "F:\pyenv\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "F:\pyenv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "F:\pyenv\lib\site-packages\discord\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "F:\pyenv\lib\site-packages\discord\client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the
developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000235D16B71F0>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
what to do?
You should read what your errors say
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the
developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
This is a bot that detect the URLs and remove URLs then finally send warning to the text channel.
it does not show any errors and not even detecting a word.
any advises?
Well this error is a bit harder tough doctor.
The user most likely used the all function on the intents object
you need message content intents
Yep, they need to add correct intents to their application, but you should at least read and try to understand your errors
I enabled it as given in docs but it isn't working. Same error
intents.message_content = True But you don't have message content intent enabled
It's working. Thanks
I also recommend setting the right event policy no one wants to see event loop closed on every error lol
It's generally ok, bot would catch all exceptions from user code/handlers anyway
True but it does look nicer.
Thank you! will try it.
Weirdly enough I don't get the same stacktrace
hi, how do i make it say the entire message and not just the first word?
async def say(ctx, message):
if message == "@everyone":
await ctx.send("Nice try buddy")
return
if message == "@here":
await ctx.send("Nice try buddy")
return
await ctx.send(message)```
Use ctx, *, message
how would i make it so that it reads 2 inputs? ik this probably isnt right but i put message2 to kinda make sense of what im trynna askasync def remind(ctx, *, message): await ctx.send(f"Reminding you about `{message}` in {message2} seconds.")
File "D:\etc\devv\bilenatorul\main.py", line 50, in <module>
async def whitelist(ctx, user: discord.Member=None):
File "D:\etc\devv\bilenatorul\main.py", line 45, in check_whitelist
if str(ctx.author.id) in f.read():
AttributeError: 'function' object has no attribute 'author'
def check_whitelist(ctx):
with open('users.txt') as f:
if str(ctx.author.id) in f.read():
return ctx.author.id
@bot.command()
@bot.check(check_whitelist)
async def whitelist(ctx, user: discord.Member=None):
if user == None:
await ctx.send("Ai uitat sa mentionezi persoana sau id-ul.")
return
def whitelisted(user_id):
with open('users.txt', 'r') as f:
if str(user_id) in f.read():
return True
else:
return False
def addwhitelist(user_id):
with open('users.txt', 'a') as f:
f.write(f"{str(user_id)}\n")
f.close()
if whitelisted(user.id) == True:
await ctx.send(f"{user} este deja in lista de useri.")
else:
addwhitelist(user.id)
await ctx.send(f"{user} a primit acces la comenzi.")
ig nobody got idea whats happening
@vocal snow can you help me with this?
you could take the seconds first and then the message later
async def remind(ctx, time: int, *, message: str):
...
so for example if i typed "$remind feed cat 600" and i want it to respond "Reminding you about feed cat in 600 seconds" how would i do that
@vocal snow
I wouldn't recommend doing this since parsing this is harder than just taking the seconds first
so i could do "$remind 600 feed cat" with this
no, you do $remind 600 feed cat
yeah
or you could do $remind "feed cat" 600
def check_whitelist(ctx):
with open('users.txt') as f:
if str(ctx.author.id) in f.read():
return ctx.author.id
@bot.check(check_whitelist)
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
oh i didnt see that
but that's not how you use it
you want it to be a global check right?
it should apply to all commands
then you should use discord.ext.commands.check
like @bot.discord.ext.commands.check?
Why do discord bots need message content intents to respond to commands?
because to see a text command you need to see the text
discord does provide content to bots for DMs and messages that mention them, so you're not completely ruined if you dont have the intent
Anyone has a good button interaction paginator? I uhm yes.
i wrote one as part of my bot, and tbf i should probably turn it into a package eventually
Alright thanks y’all I need to verify my bot and it’s asking why I need it
you should switch to slash commands
I’m not sure how to do slash commands
unfortunately they wont accept "text commands" as a reason for getting message content iirc
they won't give you message content intents if you don't have a valid reason (and text commands aren't a valid reason unfortunately)
are you using discord.py?
the latest version?
Nope
Stable version has slash commands too.
Could I "borrow" some inspiration?
Won’t I have to change almost all my code?
not really
How do you make slash commands
Ok I guess that does not look too bad
So I’m a little confused will I not be able to have text commands
no, only app commands like slash commands or context menus
Cause I still want that so I need message content intent
If you want a public bot, no. If you want a private bot, yes.
That’s crazy
it's for privacy reasons
That's called 3th party user.
So should I remove text commands?
If you want a public bot, yes.
Dang ok
its under an open source license so go ahead, the documentation isnt comprehensive but i can point to a few examples
https://github.com/thegamecracks/thegamebot/blob/v2/bot/utils/paging.py
example 1: https://github.com/thegamecracks/thegamebot/blob/v2/bot/cogs/helpcommand.py#L220
example 2: https://github.com/thegamecracks/thegamebot/blob/v2/bot/cogs/tags/__init__.py#L357
demo:
Holy, can I kiss you?
👀
i havent made the buttons customizable either but you can edit the source/subclass if you want that
if you know of the older discord-ext-menus package (reaction-based) it works somewhat similarly with different sources you can use
Can I no longer get ctx from commends
there is a Context.from_interaction i think
!d discord.ext.commands.Context.from_interaction
classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.
In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.
New in version 2.0.
it's stable, yes
Honestly I'm having a hard time understanding the code, as far as I can tell this was meant to be text based only.
I've already got a list of embeds passing them is pure pain.
Even if someone were to help, theoretically speaking, how does one "restore" a channel?
its similar to discord-ext-menus in that you're meant to subclass one of the PageSource classes and implement a format_page method that returns either a string, Embed, or dict with content/embed keys
you'll see the subclassed page sources inside my two examples
So instead of embeds I'm passing a list of page sources?
for the regular "pagination" usage you only need one ListPageSource in your case
there's two features to it, one is pagination and the other is navigation
navigation allows PageSources to return other PageSources, and when the user navigates to one of those sources it's added onto the PaginatorView.sources stack
aka nested pages
I tried using ListPageSource but I need to define page_size but embeds don't have a page size.
oh right, its meant to take a list of stuff and then chunk it into sublists for format_page to format it as an embed
So it is text based 😂
wdym
I can't pass embeds I need to pass text and use format_page to make the embed.
you can pass anything you want in the list
But not a list of Embeds.
sure you can
Then I'm doing something very wrong.
it can be as simple as this: ```py
class PassThroughPageSource(
ListPageSource[discord.Embed, None, PaginatorView]
): # list[E] S V
# first one specifies the type of each element
# in the list
def init(self, embeds: list[discord.Embed]):
super().init(embeds, page_size=1)
def format_page(self, view: PaginatorView, page: list[discord.Embed]):
return page[0]
Usage:
view = PaginatorView(sources=PassThroughPageSource(embed_list))
await view.start(inter_or_channel)```
before i give myself a headache trying in vain,,
is it possible to load a cog, from within a cog?
yes, although thats not a common use case
You didn't win lmao your a broke 10 year old living under ur mums roof
personally for my multi-cog extensions i use setup() to load the cogs
Hm I need to look this trough.
im working remotely, and just because i know for a fact i'd lose an SSH session somehwere, im running the bot on tty2 for ease of use sake, and i don't wanna have to go and VNC into my KVM in the event that i want to add a cog in the future
Please be respectful towards other members.
so i was just going to have a skeleton main.py with a reload command, that reloads a main cog where i actually set up all my cogs and keep everything organised
does it react to anything with skeleton in it? lmao
you could use the jishaku package from pypi, its got several management commands including load/unload for reloading extensions on the fly
guess so hahaha
I'm matching his energy
I don't care.
isn't that just essentially what cogs are?
cogs and extensions are very different
Actually just class PassThroughPageSource(ListPageSource): Too many arg error since class ListPageSource(PageSource[list[E], S, V]):
extensions allow code to be hot-reloaded, while cogs are merely how you organize listeners/commands together
If you have a problem with another member you have several options:
- ignore them
- block them
- report them via ModMail
- any/all of the above
You do not need to cause further disruption by "matching their energy".
The same applies to everyone.
maybe i should have also made it generic too...
adding generic types for it has been quite confusing to do
Maybe.. anyways thanks for the info I just recently started with views.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I know this would work for prefixed commands but would this work for slash like shown below?
access = [836895718563250196, 831118106876969021]
@bot.event
async def on_message(ctx: discord.ApplicationContext, message: discord.Message):
if not ctx.author.id in access:
return await ctx.respond("Only a few people have access to this bot. Kindly use @MusicBot")
else:
pass
await bot.process_commands(message)
slash commands dont send a message do they it triggers a webhook iirc
really?
is there a way that a bot can recognize voices
Why not, I was actually thinking about making voice attack for specific events lol
!paste
code is kinda rly bad atm could anyone give me opinion on how to improve + it has a lot of flaws but idk how to make it another way
is there anyway to make a python program for run 3-4 bots, i mean the program run the same code for theses 4 bots.
all this one loop
yes i suppose u could prolly run 4 diff instances of bot in 4 diff threads coz the only thing changing would be the token
altho i dont see the use case
u could use a single db connection instance through ur bot instead of making multiple connections over the code
it is not working but why?@bot.command(name="ping") async def test_msg(ctx): await ctx.send("pong")
I only make 1 connection
