#discord-bots
1 messages · Page 3 of 1
Yeah that’s a bit of a problem since it has to be asynchronous
yea
ive also been trying to open a .bat file from the discord bot
could u help me with that?
ok or not

what is wrong? i want to get speedtest infos and write it to chat
n = input("Enter your id")
channel = client.get_channel('n') Why doesnt it work?
get_channel(n)
you're trying to get the channel from a string n
not the variable you created
@wispy sequoia
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
code
`n = input("Enter your id")
@client.event
async def on_ready():
print("online")
@client.command()
async def test(ctx):
channel = client.get_channel(n)
await channel.send("pls work for god sake")`
!code
await client.get_channel(n)
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
how can i get cmd output?
also y are u using input()
other PPL cannot type in terminal💀
im testing only for now
@shrewd apex ayo, question, is it normal for Client.close() to raise an error?
i just want it to look fancy
client = ?
@client.event
async def on_ready():
print("online")
@client.command()
async def test(ctx, server):
serverid = int(''.join([i for i in server if i.isdigit()]))
channel = client.get_channel(serverid)
await channel.send("pls work for god sake")
Well thats above my iq level
okkk
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
what's the error
RuntimeError, someone told me it's normal
@app_commands.command(name='play',
description="Test Play")
async def play(self, interaction: discord.Interaction):
server = interaction.guild
voice_channel = server.voice_client
if not voice_channel: # if client isn't connected to any VCs
user_vc = interaction.user.voice # get user's voice state
if not user_vc: # if user isn't connected to any VCs
await interaction.response.send_message("You are not connected to a voice channel")
return
destination = user_vc.channel
audio_source = discord.FFmpegPCMAudio('song.oog')
voice_client = await destination.connect()
voice_client.play(audio_source)
await interaction.response.send_message("Playing")``` I'm trying to make this play command that plays my file except it doesn't really do much and I cannot figure out why I get no errors and I'm running the newest version of 2.0
@client.event
async def on_ready() -> None:
print("online")
@client.command()
async def test(ctx: commands.Context, channel: discord.TextChannel) -> None:
chan = client.get_channel(channel.id)
await chan.send("pls work for god sake")
slightly better looking
ahhhhh yes commands.Context, I love it
ytdl?
what my code does it sending a message to the specified channel in terminal , i think ur solution doesnt serve that ?
im not sure im a newbie
Not anywhere close to YouTube DL I'm playing a file off my computer
why do u want to enter the channel in the terminal
to do testing
just testing :p
YouTube DL brakes terms of service I'm not willing to deal with that
oh idk y u want to but lemme modify it
This is an old song I created
does it connect to your voice channel?
thankss
@client.event
async def on_ready() -> None:
print("online")
@client.command()
async def test(ctx: commands.Context) -> None:
channel = int(input('enter channel id here:'))
chan = client.get_channel(channel)
await chan.send("pls work for god sake")
No
assert voice_channel is None after defining voice_channel and see
did u do prefixtest in the server which ur bot is?
or do u just want to ask input directly and run the command
i did but ill have to give him the id for that which my terminal doesnt ask
as soon as bot starts
don't add anything in on_ready 💀
i gotta do ,test lol
...
worked LOL thanks
yeah it's fine
so py voice_channel = server.voice_client assert voice_channel is None
fix the indentation but yeah
async def test(ctx: commands.Context) -> None: || can you explain this tho.. its very different than this || async def test(ctx, server):
Nope, did not work
yes it's asycronous
did it raise AssertionError
many people can use the command at the same time
No
thats what makes it async
ohh thanks
do you have an error handler
I've been told it's probably because of the new logging system which I know nothing about
No
and do you have logging setup?
I think you should do that then
Can't find documentation on it. I know nothing about it
@slate swan how can i make it do that on start
thx
lmao nice ping
oh lol just noticed
ashley love mistake
@client.event
async def on_ready():
print("online")
serverid = int(input('enter channel id here:'))
@client.command()
async def test(ctx) -> None:
channel = client.get_channel(serverid)
await channel.send("pls work for god sake")
client.run(token, bot=False)
@client.event
async def on_ready() -> None:
print("online")
channel = int(input('enter channel id here:'))
await test(channel)
async def test(channel) -> None:
chan = client.get_channel(channel)
await chan.send("pls work for god sake")
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
how can i add that sunucuya ekle button to my bot
(Sunucuya ekle means add to server)
from discord dev portal
In this video, I'll show how to get the Add to Server button on your bot's profile in less than a minute.
If you have any suggestions for future videos/doubts, leave it in the comments below. I might not be able to answer everyone but you can join my discord server for help: https://discord.gg/TXF3hBj
▬▬▬▬ Useful Links ▬▬▬▬
Discord Developer ...
thats the only good tutorial he has which don't use json 💀
thank you
Lmao u started sharing yt links?
ashley whats this TypeError: test() missing 1 required positional argument: 'channel'
code
u didn't copy my updated code
oh lemme see I think i forgot ctx
you naughty
is there any way to make it invite people to bots main server?
@slate swan
I keep on getting start gotten unexpected keyword log handler
;-;
but thats the error
oh are you not using 2.0?
umm no u could make an invite command tho
i changed the code
I am using 2.0
ohh
await bot.start("token", log_handler=handler)```
k thanks
@shrewd apex : Command "test" is not found //what the command
it's a method of run, not start
that's fine, check the last example on that page
just don't pass the log_handler and it'll be fine
@client.event
async def on_ready() -> None:
print("online")
channel = int(input('enter channel id here:'))
chan = client.get_channel(channel)
await chan.send("pls work for god sake")
replace it all right
Okay, well I don't see this logging anything so that's a problem
@shrewd apex ommggg worked
i should actually learn abt these and not spend more time on stackoverflow lol
Everything in the example has client.run
ye, it doesn't matter
but anyways, I would figure out where in your command the code is crashing
Now i will try to make it send a message to multiple channels wish me luck
maybe add a few prints/asserts and see
@bot.command()
async def yardım(ctx):
embed= discord.Embed(
title = "Fly Bot yardım komutu!",
description=
f"""
Merhaba, {ctx.author} Komut listem şöyle: \n\n\n
Genel kullanıcı komutları; \n\n
**Stats**(botun istatistiklerini gösterir) `i!stats`\n
**Davet**(botun davet linkini gönderir) `i!davet` \n
**Uptime** (botun ne kadar süredir aktif olduğunu gösterir) `ì!uptime` \n
**Ping** (botun anlık gecikmesini gösterir) `i!ping` \n
**Yankı**(bot sizin mesajınızı taklit eder) `i!yankı [mesajınız]` \n
**Hesapla** (çok argümanlı hesaplar yapmanızı sağlar) `i!hesapla [5 + 10]`
"""
)
await ctx.send(embed=embed)
what is wrong?
Yeah but in all the examples it has them starting the logger inside of the client.run do you not think that's a problem?
also how can i close that setting? (i don't want yellow highlight)
@shrewd apex now can i do like this --- n = int(input("Enter number")) then do a range(n) so it repeats n times??
the whole code
Hey @vocal snow!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
mf
can u send ur whole code
pain
that's all code.
import discord
from discord.ext import commands
it isn't a problem, passing it will use discord.py's default configurations but if you don't pass it you can use your own
smh
Lol
you could also try decreasing the level, to logging.DEBUG or something
In 2.0, anything previously printed like errors from error handlers are now logged instead.
Logging is set up for you if you use Client.run, but you'll need to do it yourself if you use asyncio.run.
Something about that tells me it's not going to log it automatically
i don't see anything wrong at best i would say use f strings and color kwarg for looks try to save ur code and restart ide
it won't, that's why you use the example they gave you (in the last case)
I use the example
what i have ```py
import logging
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')```
anyone have a link to a discord.py 2.0 eval command? my 1.0 doesnt work anymore
Did you use the right URL? 401 Error code means you weren't authorised to make a request to that URL
i removed f string ,nothing happened. (i'm using doki theme pack so my colors are not same as your)
not that one, the last one
no i meant color for discord.Embed()💀 but i don't see anything wrong in ur code
Try using some other URL to see if it works, there is no error in your code itself, the error is related to the URL and the authorisation needed to request it
ah lol, i see. i didn't see too but not working that d*mn thing
@client.event
async def on_ready() -> None:
print("online")
n = int(input('Amount of channels'))
range(n)
channel = int(input('enter channel id here:'))
chan = client.get_channel(channel)
await chan.send("pls work for god sake")
``` Why doesnt it repeat n times.
what do i have to put in the emoji= to get this?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Wow, that's a lot of info
print('Hello world!')
@client.event
async def on_ready() -> None:
print("online")
n = int(input('Amount of channels'))
range(n)
channel = int(input('enter channel id here:'))
chan = client.get_channel(channel)
await chan.send("pls work for god sake")
range(n)
...
``` is not valid syntax
What do i have to do
It should be ```py
for _ in range(n):
...
oh yeah i saw that in stackoverflow i dont know what to put in _
hopefully u are not but i get a feeling u are self botting
never.
voice_client = await destination.connect()
AttributeError: 'NoneType' object has no attribute 'connect'
_ is just a variable which semantically means, "un-used"
say no to self botting
otherwise no need to take in terminal
I suggest you review some of the python basics, especially if you are willy nilly putting together code like that where it doesn't even have valid syntax
u could just put those other lines instead of the ... in what while(1) sent
Not that you need to listen to me at all, just a suggestion
worked.
my bot is done
so looks like user_vc.channel is None :)
So it's saying that my bot's not in a voice channel?
interaction.user.voice, so the command author is not in a vc
Bs
Function to delete a channel? Anyone know
I am in a voice channel
Okay well that solves that issue. Discord is just being a pain
Were you in a voice channel then restarted your bot?
In that case due to the limitations of the API you'll have a "dead-cache"
bot timeouting member in 2 seconds
So the wrapper doesn't think there is a user in the voice channel
Okay, I still have the problem where it's not playing though
The box in the channel but there's no sound
I don't really see a trace back in regards to this @vocal snow
@client.event
async def on_ready() -> None:
channel = int(input('Enter channel id here = '))
chan = client.get_channel(channel)
await chan.send("pls work for god sake")
``` How can i make it so i add the channels directly to code so i wont have to type them?
Why do you need to send a message to multiple channels? 🤨
use a list
Add a wait_until_ready also
whats that good for
unhashable type: 'list'
mylist = ["1000832234045067275", "1000832258481066004", "1000832281084186644"]
@client.event
async def on_ready() -> None:
print("online")
n = int(input('Amount of channels'))
for _ in range(n):
chan = client.get_channel(mylist)
await chan.send("pls work for god sake")
@client.event
async def on_ready() -> None:
print("online")
mylist = ("1000832234045067275", "1000832258481066004", "1000832281084186644")
chan = client.get_channel(mylist)
await chan.send("pls work for god sake")
``` i did this now 'NoneType' object has no attribute 'send'
It needs to be integers, not strings
oh how can i make it for strings
Remove the "", easy peasy
@scarlet flame ```py
@client.event
async def on_ready() -> None:
print("online")
mylist = (1000832234045067275, 1000832258481066004, 1000832281084186644)
chan = client.get_channel(mylist)
await chan.send("pls work")
what's this about?
sending a message to 3 channels
why did you ping me specifically
oof
Gotta loop over it and do it individually
oh imma look on a tutorial
question
@commands.Cog.listener()
async def on_raw_message_edit(self, payload):
"""Message edit event"""
if payload.guild_id != 905457759099682868:
return
message = payload.cached_message
await self.bot.get_channel(999611077094543440).send(
embed=(
disnake.Embed(
description=f"**Message edited in {self.bot.get_channel(payload.channel_id).mention}**\n**Before**\n{message.content}\n**After**\n{message.content}",
color=0xFF470F,
timestamp=datetime.datetime.now(),
)
.set_author(
name=f"{message.author.name}#{message.author.discriminator}",
icon_url=message.author.avatar.url,
)
.set_footer(
text=f"Author: {message.author.id} | Message ID: {payload.message_id}"
)
)
)
how do I get the message before the edit?
Slash commands don’t have a message attribute. Try just ctx.author
Im not actually sure if d.py commands use Context objects
They might use Interaction objects
Yea they use interaction objects
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
This one is disnake btw ^^
Nah, thats d.py
.topic
Suggest more topics here!
own voice channel like that creates a voice channel if you join one
!d datetime.datetime.utcnow
classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.
This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now").
Warning
Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
do you think this bot is worth releasing to the wild, you enter calories and weight each day and it records and plots a graph
if you add multiple times in a day, the weight will average and the calories will add on to each other 
thats pretty cool
you can make the table on top a little prettier with https://pypi.org/project/prettytable/ maybe
How to do something when you click on a button with customid (rule_btn) write for example (Rules!) and when you click on a button with ustomid (knowledge_btn) write for example (knowledge!)
anyone know why i get No module named 'discord_slash' when i run
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_choice, create_option
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
client = commands.Bot(command_prefix="!")
slash = SlashCommand(client, sync_commands=True)
@slash.slash(
name="hello",
description="Just sends a message",
guild_ids=984307692946460702
)
async def _hello(ctx:SlashContext):
await ctx.send("World!")
#TOKEN
client.run(os.getenv('TOKEN'))
I already installed libraries with pip3 install discord-py-slash-command and pip3 install discord
#media-processing please
FYI discord.py supports slash commands so there's no need
thanks, i will look into it!
is this accurate?
How to make bot respond to messages containing word
or exaple keyword is "ok"
he should respond to " Ok, thats epic", but not to "Well, Okay"
February 17
Dpy is back in buisness since june/may
Supporting slash cmds buttons and all that
if message.content == 'keyword'
but will he then respond to "123okay"? Cuz I dont need it
and what about case?
if 'keyword' in msg.content.split(' '):```
This will respond if the keyword is a seperate word anywhere in the msg
no, usually a sentence
i've given you that to build off of.
If msg.content.lower() == 'keyword':
Ye idk figure it out its not that difficult
Kinda spoonfeeding
and split?
noob here
async def on_message(message)
this will make sure your bot receives the message first of all
Dont forget process_commands
and not "oK", "OK, "Ok"
.
.lower() converts string to lowercase
what does it do
but thats only if message = keyword
wrong message
Its recommended to add it to on_message
Btw split will make it respond if word is in sentance
yes
"Thats ok" will trigger it
Or smth including ok
Ye thats cool ig
I mean if you dont use prefix commands then its not needed
message.content.lower().split(' ')
thanks dude
👍
async def on_message(message):
if message.content == 'ok':
await message.channel.send('Hello')```
shrek already helped me ty xoxo
it's only going to respond to lowercase 'ok'
theres really not a need for .lower function or other modules
you can fix it by converting twice
i fixed it , had to remove the int
i used float too but didnt work
id = int(float(input('id = ')))
any1 knows how I can make my bot mix/merge 2 user names together and send it on the channel. Lets say I used the command which joins Usernames, and the usernames Bxlyn and Srrap were mentioned, how can I make it send something like Bxrap
how can i make so after i type something in consoles it instatly disspears, only applying to that line
like add the 2 usernames at random?
well not at random but
like first 3 letters of the first
and last 3 letters of the second
take the first 3 letters of the first and last 3 of the second
name = name[:3]
username = username[-3]```
name + username ?
I just did thanks to you
Yw 😁
client.user.name why doesnt this work?
I took some advice on several days ago in regards to creating a dictionary to loop through my emojis and respective ids for a reaction role post, I am able to iterate through the dict fine but my if statement is definitely not right as it goes straight to the else statement , https://paste.pythondiscord.com/qiqocalime full code is here if anyone knows where I am going wrong 🙂
Here's where the problem lies:
if emoji == Roles1.items():
...
emoji will be **one **of the emojis inside your Roles1 dictionary, while Roles1.items() will be, simply put, your **entire **dictionary in a List[Tuple[str, int]] format
So no matter what, an emoji as a string will never be equal to the entire dictionary
Also as a word of advice, the ReactionRoles command should only set up the embed, send it, and add the appropriate reactions. You should have a seperate on_raw_reaction_add listener inside your cog that handles giving the user the roles they requested
Fair enough, back to drawing board I go for learning.. 🙂 dont think I'm quite there yet and OK, I'll also give that a shot too 😄 sounds like a much better idea.
No problem. Feel free to ping me anytime with any follow up questions you may have
Doesn't work how?
it did now
Sorry to bother, would it just be this that goes under the @commands.commands:
async def on_raw_reaction_add(self, payload): ```
Exactly like so, yes! 🎉
d.py 2.0 optional slash command parameter?
@tree.command(name="rank",description="Check your level and XP.",guild = discord.Object(id=GUILD_ID))
async def self(ctx: discord.Interaction, user:discord.User):```
wanna make user optional
Set a default value
Set it to None
How can i count a runned jar files on vps?
why in isnt working
when im write my command without all args this check isnt working
whole code pls
Why? That's probably where the issue is
Since the whole thing is in a try/catch block, it exits when it encounters the missing variable and goes into the catch block section
yeah
u have try expect
I removed the extra code with variables at the beginning of the command code to show the checks
Well, put those back in and see if it works
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
yeah see
A better example would be this:
!e
try:
print(variable_that_does_not_exist)
print("This is another line. it should not get called")
except:
print("oopsies, there was an error!")
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
oopsies, there was an error!
does not work
code
Hey
Is there a easy way to change a button type to "Disabled"?
Or do i need to make a whole new view
You can edit the view you already have, then resend self
yeah button.disabled = True
Tyty
then also send or edit something
!paste it's getting hard to see, please paste all the code in the function here please
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.
anyways ill go and prepare for my science exam today
good luck with that
thanks 👍
Use a bare except instead, and see if you get any errors
try:
...
except:
...
instead of
try:
...
except Exception:
...
nothing changed
Try re-raising the error inside the except like this:
try:
...
except Exception as e:
raise e
nothing...
Looks like there are no errors then
lol
can u send the code again
And did you run the command after re-raising the error?
Because just changing it like I said won't do anything
what are you talking about?
Did you run the actual command in discord after making the changes I told you to make?
The point of this is to try to get the error handler working properly so that we can see if any errors happened
of course
i understand
Prob should of specifiied, im doing it from outside the button, so this wont work. Editing it from the msg id
And you didn't get any errors while running the command after making the changes?
i do everything you tell me and try to use the command again
0 errors
Can you add a print statement before await ctx.message.delete(), and after if member is None?
i have a question , i have a reload cogs cmd and whenever i try to reload when it comes to reload the helpbot.py it raises error Extension helps is not loaded" (its not hardcoded)
So:
if member is None:
print("works")
await ctx.message.delete()
...
does helps is already something or what
does not display this, I am just trying this now and nothing
if I remove some function arguments, remove checks for them and the code that uses them and try to use the command?
u tried this?
can u show how did u called the cmd in discord
Okay.. let's see if the command callback is actually getting called in the first place. Add a print statement as the first line in your command:
@commands.command()
@commands.has_permissions(administrator = True)
async def remute(self, ctx, member: discord.Member = None, amount: str = None, reason: str = None):
print("command called")
log = Logs(ctx)
...
yeah
And call the command again in discord and see if it prints that
any idea robin?
wait
Move it down because member won't be defined there
actually nevermind
was confusing myself with author
hm
.
@sick birch :white_check_mark: Your 3.10 eval job has completed with return code 0.
True
what
lol
None is None is true since theyre the same instance
Except for some reason it's not
looks like we broke python
anyone got any idea
the only other thing i can think of is your command is freezing up before it gets to the if member is None part
if none == none
print(‘True’)
gottem
i will add try except to all code before checking
yeah try printing print(member is None)
do like
#code
print(1)
#code
print(2)
#code
print(3)
#code
print(4)
it's the same exact condition you have later on
@terse coyote
@commands.command()
@commands.has_permissions(administrator = True)
async def remute(self, ctx, member: discord.Member = None, amount: str = None, reason: str = None):
print(member is None)
log = Logs(ctx)
...
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
caught in 8k
i'm grasping for any leads at this point
a is literal to the instance of NoneType lol
ikr
because either something is freezing up the command or we managed to break python itself
or maybe you're having a big brainfart and you should go to sleep
and i'm really not in the mood to go fill out a GH issue on cpython
what u guys think it is ???
I FIND IT
GG
what was it?
same
are you sure you want to see it?
😉 indeed
flashbacks to that one time i spent 30 minutes helping someone and they didn't save file
💀

'NoneType' object has no attribute 'mention'
cool
my embeds....
very nice
I thought you weren't getting any errors?
but why isnt it raising error
before check member is None...
u do add exception right
nice
yeah
okay but... how come you didn't get this error before?
Asking again as i didnt explain right and got no response to my reply lol
i need to edit a button to disabled via a message object(whitch has the button view), not sure if im dumb orrr not thinking striaght lol, any ideas?
maybe he's hiding something
for some reason i am not getting any errors in the console lately...
why? idk
sure?
Faulty error handlers maybe
thats very weird
^ lol
?
Could you give more context? Existing code would be helpful. When do you need to disable button?
The function name is misleading
That's fired on any error, not only on MemberNotFound
Rename it so you don't confuse yourself, add an else: raise error
`havnt coded it yet
im making a quote system, once the user accepts a quote, it loops thru the db whitch has all the msg ids of quotes, and edits the buttons to disable
So once a user clicks the "accept" button, it should disable?
Yes + all other quotes
Whitch would be in the db, with a list of msg ids
That would be disabled inside of the view, wouldn't it?
So just button.disable = True and resend the view
But button.disable would just be the button in the view, for accept
Not each accept button
How many buttons are you planning on having per message?
It did not help(
Accept and reply in each quote message
So two
button would actually be the button object that was clicked by the user
Yes and that would only disable the button in the quote clicked tho right?
Not the rest of the accept buttons in other msgs
And the rest of the buttons that need to be disabled are in other messages?
Yes
Whitch the msg ids are stored in the db
Meaning i get_message loop, but i dont know how to edit the button to disabled from that poiint on, unless theres a other way
Okay, you should be able to loop over each of those message objects, and use discord.ui.View.from_message(message) and go from there
Or actually you can just create a static view with the accept button disabled, and edit each message with that
Oh yeah true, i thought of that but lost my trace of thought lmao
tysm!
Not sure if that works tho unless you can make a button disabled by default when making the view
As i thought only button.disable or what ever is the only way
yep, just pass in disabled=True
i wanna make a command which shows all users with a timeout and until what time it will be, but when i'm using a command bot send users in different messages
code:
for memb in ctx.guild.members:
member = ctx.guild.get_member(memb.id)
if member.is_timed_out() is True:
x = [member.mention]
mentions = f"until <t:{int(round(member.timed_out_until.timestamp()))}:R>\n".join(x)
embed = discord.Embed(description = f"{mentions}")
await ctx.send(embed = embed)
can someone help with this? i wanna remove t1 and t2 from a set in an error handler if a command times out, but it is not removing them
does discord.py have a timeout feature?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
thank you.
Also, I read that discord.py was discontinued. How does this affect bot development? I'm a beginner
it got resumed!
It was, but a while ago the dev got back to it and is actively working on discord.py 2.0 iirc. All our bots use discord.py still
oh, awesome
is it considered dpy 2.0?
Hi im coding in hikari and hikari-lightbulb if anyone is familiar with that, also first time using sqlite3.
import lightbulb
import sqlite3
plugin = lightbulb.Plugin('rep')
@plugin.command
@lightbulb.option("item", "the item you bought / sold")
@lightbulb.option("vendor", "the person you are vouching for", type=hikari.User)
@lightbulb.option("did_you_buy", "did u buy an item or sell it? BUY = TRUE SELL = FALSE", type=bool)
@lightbulb.option("rating", "The rating you are giving to the seller out of 10 ex, 8 = 8/10", type=int)
@lightbulb.option("money_spent", "The amount of usd u spent on the transaction (DONT PUT A $ BEFORE)", type=int)
@lightbulb.option("message", "Extra things you want to tell people about")
@lightbulb.command("rep", "reps somebody!")
@lightbulb.implements(lightbulb.SlashCommand, lightbulb.PrefixCommand)
async def embed_command(ctx: lightbulb.Context) -> None:
if ctx.author.id == ctx.options.vendor.id:
embed=hikari.Embed(title=f"**You can't vouch for yourself!**", description=f"Try to rep somebody else!", color=0xFF0000)
embed.set_footer('Made by cantthinkofausername#3155')
embed.set_thumbnail(ctx.author.avatar_url)
await ctx.respond(embed)
bought = "Bought"
if ctx.options.did_you_buy == False:
bought = "Sold"
if ctx.options.rating > 7.99:
color = hikari.Color(0x00FF00)
elif ctx.options.rating > 4.99:
color = hikari.Color(0xFFFF00)
elif ctx.options.rating > .99:
color = hikari.Color(0xFF0000)
embed=hikari.Embed(title=f"**{ctx.author}'s Vouch**", description=f"Being vouched: {ctx.options.vendor.mention}\nTag: {ctx.options.vendor}\n Item {bought}: {ctx.options.item} for ${ctx.options.money_spent}\nRating: {ctx.options.rating}/10\nMessage: {ctx.options.message} ", color=color)
embed.set_footer('Made by cantthinkofausername#3155')
embed.set_thumbnail(ctx.author.avatar_url)
await ctx.respond(embed)
con = sqlite3.connect('example.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS reps
(voucher text, rating text, money_spent text)''')
con.commit()
for row in cur.execute('''SELECT * FROM reps'''):
print(f'{ctx.author} {ctx.options.rating} {ctx.options.money_spent}')
def load(bot):
bot.add_plugin(plugin)
The command is a rep command, and just makes vouching somebody look better, im trying to add all vouches into a database with the important info. the rep command works fine but the problem is it doesnt enter anything relevant, sqlite code below,
`con = sqlite3.connect('example.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS reps
(voucher text, rating text, money_spent text)''')
con.commit()
for row in cur.execute('''SELECT * FROM reps'''):
print(f'{ctx.author} {ctx.options.rating} {ctx.options.money_spent}'`
I opened the database but this is all i see is this:
why are you trying to read a sqlite file with notepad
bc when i double clicked it, it didnt open automatically so i just chose the first program
is there a specific program i should be using?
how can i make a sub command in discord.py 2.0
use this to check your data https://sqlitebrowser.org/
the
the app right?
yeah its a ui to view sqlite or db files
same as old way?
Yes, very helpful
It really is
i see you're new here, so do take a close read of our #rules and #code-of-conduct for the expectations of our community
oh sorry
no problem, we just like to focus on being very welcoming, helpful, etc.
sure a lot of things can be googled, or trial and errored, but, we are a real time chat community so it's nice to bounce ideas with another people and just ask questions to a real live person
imo there isnt really a point in helping when there isnt a problem
that allows for follow up questions and learning opportunities for others as well
thx for listening
@client.event
async def on_raw_reaction_add(payload):
for role, msg, emoji in client.reaction_roles:
if msg.id == payload.message_id and emoji == payload.emoji:
await payload.member.add_roles(role)
I'm getting
AttributeError: 'str' object has no attribute 'id'
why did you choose on_raw_reaction_add over on_reaction_add?
cause on_raction_add won't work if there's no message in cache?
do you know what's the problem with my code?
no i've never used the raw version, i have a similar code snippet in my bot which does pretty much the same task
don't know if it can help but here it is anyways
msg is a str, not a discord.Message obj
Is making a sub command the same in version 2.0 as it was in 1.7?
yeah it's fine if it does the same task
so i have to define msg?
Can you point me in the right direction for this? I cannot find documentation on it
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
You'll need a group to make a subcommand unless I'm misunderstanding your question
I just want to make sure I'm reading this documentation right? If I want them to be a sub command, they all need to be in the same class for the same subcommand? Right?
Right, you subclass app_commands.Group and you can use the app_commands.command decorator to create subcommands inside it
Okay, this does not seem very hard, but I also want to make sure of one more thing. Inside of the examples I'm looking at. It has app_commands.describe. is that required?
Nope, it just allows you to have a description for the command parameters
so somthing like this??? ```py
class MyGroup(app_commands.Group):
stats = app_commands.Group(name='c_photo', description='Get tag statistics')
@app_commands.command(name='winter',
description="Winter photos.")
async def winter(self, interaction: discord.Interaction):
with open("json/holidays.json", "r") as file:
json_dict = eval(file.read())
answer = random.choice(json_dict['Winter'])
em = discord.Embed(title="Happy Winter", description="", color=0xff6804)
em.set_image(url=(answer))
em.set_footer(text=f"Echo discord bot")
await interaction.response.send_message(embed=em)
@app_commands.command(name='christmas',
description="Christmas photos.")
async def christmas(self, interaction: discord.Interaction):
with open("json/holidays.json", "r") as file:
json_dict = eval(file.read())
answer = random.choice(json_dict['Christmas'])
em = discord.Embed(title="Happy Christmas", description="", color=0xa32a2a)
em.set_image(url=(answer))
em.set_footer(text=f"Echo discord bot")
await interaction.response.send_message(embed=em)```
Because I don't see those popping up as a subcommand
add_command(command, /, *, guild=..., guilds=..., override=False)```
Adds an application command to the tree.
This only adds the command locally – in order to sync the commands and enable them in the client, [`sync()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.sync "discord.app_commands.CommandTree.sync") must be called.
The root parent of the command is added regardless of the type passed.
so tree.add_command(MyGroup())
Yep
In my main file or in my cog?
Wherever you have access to tree
Okay but if I put it in my main file where has access to tree I get my group is not defined
Inside of the cog it says that tree is not defined
Could you show your code?
class MyGroup(app_commands.Group):
stats = app_commands.Group(name='c_photo', description='Get tag statistics')
@app_commands.command(name='winter',
description="Winter photos.")
async def winter(self, interaction: discord.Interaction):
with open("json/holidays.json", "r") as file:
json_dict = eval(file.read())
answer = random.choice(json_dict['Winter'])
em = discord.Embed(title="Happy Winter", description="", color=0xff6804)
em.set_image(url=(answer))
em.set_footer(text=f"Echo discord bot")
await interaction.response.send_message(embed=em)
@app_commands.command(name='christmas',
description="Christmas photos.")
async def christmas(self, interaction: discord.Interaction):
with open("json/holidays.json", "r") as file:
json_dict = eval(file.read())
answer = random.choice(json_dict['Christmas'])
em = discord.Embed(title="Happy Christmas", description="", color=0xa32a2a)
em.set_image(url=(answer))
em.set_footer(text=f"Echo discord bot")
await interaction.response.send_message(embed=em)
tree.add_command(MyGroup())
If this is in an extension file you can add it in the setup
bot.tree.add_command(...)
up hear at the top???? ```py
class fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
print("cogs.fun")
bot.tree.add_command(MyGroup())```
That works too, although I'd do it in the setup function instead
async def setup(bot):
bot.tree.add_command(MyGroup())
bot.tree.add_command(MyGroup2())
await bot.add_cog(fun(bot))```
Because I still don't see the commands registered
You're syncing the tree?
Tree syncs in the main file
async def sync_commands(bot):
await bot.wait_until_ready()
await bot.tree.sync()
for guild in bot.guilds:
await bot.tree.sync(guild=guild)```
It’s better to sync globally
Discord doesn’t want u to do it for every guild and there’s no point honestly
Maybe if you wanted to disallow dm commands
Well that's not really the goal for at this second. The goal is to get The command working as it currently work. There's no reason to change it right this second as the bot is only in one Discord
That’s fair
I will change it for my main bot because I did forget to do that when I released but for the test bot which is what I'm currently on no reason to
you're syncing after you load the extensions right
Yes
/c_photo winter
the group is MyGroup/MyGroup2 though
Lol had no idea. That's how that worked
if you want the name to be c_photo: ```py
MyGroup(name="c_photo")
Now I can still name a regular command c_ photo correct?
i dont think so
What's the point of a sub command if you don't have a regular command that's named that first?
Either way, we're about to find out cuz I'm about to test it
it'll show up as /group subcommand in the menu
but i dont think you'll be able to have /group as a standalone
you'll have to ask in the dpy server about that, im not sure if theres a way to do it or not (there might be)
Yeah I'ma stay out of there right now. They don't particularly like me
tbf they dont like anyone
Good to know. I asked apparently way too many questions because they super confused me earlier and then told me to go learn basics
sounds like the dpy server xd
I was told you've been in here for 3 years now and you don't know basics yet. I was like you confused me
it does seem like you can have the group as a standalone command https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Yeah, I just found out a different way to organize everything that still made sense
I just known the old version. You could do that
yeah that's pretty common in that server. just have to ignore it
most people there like feeling like they're smarter than you if you don't understand something
Well it just makes me annoyed because the command that they were helping me with I never finished and so it's kind of like just going to sit dormant now until I figure out what I'm doing with it and why it's not working
same
dont ask there. the server is full of toxic people
they were toxic to me 🗿
no you're just bad at asking questions 
also just because a few people were toxic to you, doesn't mean it's always toxic. im really active in the dpy server and i help in the help channels alot and i dont see toxic people that often at all.
so dont say "dont ask there" or "it's full of toxic people" when it's really not, k thx
it does have a reputation for being toxic 🤷♂️
eh fair but that doesn't mean it always is.
true, it has also gotten less toxic in recent times
imo i feel like every support server for helping with coding has somewhat of a reputation for being toxic tbh, well from what i've experienced there is a toxic side to every support/coding help server for some odd reason 
oh hey humble

hi
im pointing this at most of the discord support related servers in general 😭
Im always toxic
How would I scan through member list and ban someone if “user” in username
Since I got raided by someone who used same name on all users
iterate over guild.members and check if "user" in member.name; then use member.ban()
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
Ok thanks
@vocal snow
```for guild in bot.guilds:
for member in guild.members:
if "tetsty" in member:
await member.ban()```?
also u don't want to do that if u have a big bot across many servers
It’s only 1 bot
And it’s for removing someone who raided
fine then👌
why does a discord bot take so long to go offline when i shut it down?
Bc it’s sorta web based so it has to send request to server to tell it to die
It worked all of them are gone
👍
Wait will I be banned for spamming discord api for mass ban?
There was loads of them
Na I’m not that’s good
how can I make my bot change it's own pfp?
!d discord.ClientUser.edit
await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") is given through the use of `fp.read()`.
The only image formats supported for uploading is JPEG and PNG.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
!d discord.ext.commands.Bot.user is an instance of ClientUser
property user```
Represents the connected client. `None` if not logged in.
its content
what dose that mean
you typed msg.contect instead of msg.content
would this code be right before i run it? Im using hikari lightbulb and im trying to get the traceback of the error to send to the user ids dms
@errors_plugin.listener(lightbulb.CommandErrorEvent)
async def on_error(event: lightbulb.CommandErrorEvent) -> None:
exception = event.exception
users = [
event.context.cache.get_user(user) for user in [690631795473121280, 994738626816647262]
] # 1: main, 2: second
if isinstance(exception, lightbulb.CommandInvocationError):
await event.context.respond(
f"Something went wrong during invocation of command `{event.context.command.name}`."
)
for user in users:
await event.context.respond(
embed = hikari.Embed(
title=f"An unexpected `{type(exception).__name__}` occurred",
description=f"`/`/`py\n{''.join(format_exception(exception.__class__, exception, exception.__traceback__))}`/`/`"
)
)```
I have a really weird question
same
Can I run two separate codes on one single bot (maybe in different languages too)?
These codes should work independently from each other (same prefix tho)
my question is i wrote this but i dose not work
`import discord
from grapheme import startswith
from discord.ext import commands
token = "Token"
client = discord.Client()
client = commands.Bot(command_prefix = ".")
@client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
@client.event
async def on_member_join(member):
print(f'{member} has joined the server !')
@client.event
async def on_member_remove(member):
print(f'{member} has left the server !')
@client.command()
async def ping(ctx):
await ctx.send("pong!")
@client.event
async def on_message(msg):
if msg.author != client.user:
if msg.content.lower().startswith("hello"):
await msg.channel.send(f"Hi {msg.author.display_name}")
client.run(token)`
What is the error?
when i run this and i type .ping it the bot dose not reply with pong
Put Ping command all the way down
and when someone join or leave it dose not print
Hmm
Somebody help this cool guy
?
`import discord
from grapheme import startswith
from discord.ext import commands
import random
token = "token"
client = discord.Client()
client = commands.Bot(command_prefix = ".")
@client.event
async def on_message(msg):
if msg.author != client.user:
if msg.content.lower().startswith("hello"):
await msg.channel.send(f"Hi {msg.author.display_name}")
@client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
@client.event
async def on_member_join(member):
print(f'{member} has joined the server !')
@client.event
async def on_member_remove(member):
print(f'{member} has left the server !')
@client.command()
async def ping(ctx):
await ctx.send(f'{round(client.latency * 1000)}')
@client.command(aliases=['8ball', 'test'])
async def _8ball(ctx, *, question):
responses = ['yes', 'no']
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
client.run(token)`
this code when i run it
where ur intents
and when i type .ping or .8ball it dose not respond anything to me
you mean pip ?
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '!')
@client.event
async def on_ready():
print('Bot is online')
@client.event
async def on_member_join(member):
print(f'{member} has joined the server!')
@client.event
async def on_member_join(member):
print(f'{member} has left the server')
client.run('Token')
it does not show when a member joins
any help pls?
also if u have on_message event do await client.process_commands(message) at the end
where are ur intents? ;-;
how do i enable it?
@shrewd apex i didnt get what should i have to do
u enable in dev portal and in code u do commands.Bot(command_prefix=,intents=discord.Intents.all())
i didnt get it
ok
thanks!
where in dev portal
where u made the bot
i know in the site
but im asking like where XD am i so stupid or you guys are so genius
and what should i do with ' in code '
just checked In the bot section and scroll below
client = commands.Bot(command_prefix = '., intents = discord.Intents.all())
thank you so much
btw thanks for helping
👍
guys should i just use text files to store users data like if someone use the command "!start playing" for the first time i create a dictionary and put his stats there and whenever he uses specific command the values inside that dictionary increases....or is there any kind of database program for discord bots?
can someone help
run it and find out?
I did, but it didnt work and i cant see the error
thats why i asked if the code was correct
guys one more thing i need help
`import discord
from multiprocessing.connection import wait
from grapheme import startswith
from discord.ext import commands
import random
token = "token"
client = discord.Client()
client = commands.Bot(command_prefix = '.')
@client.command()
async def clear(ctx, amount=10):
await ctx.channel.purge(limit=amount)
client.run(token)`
this dose not work
i mean like when i type .clear it dose not work
error?
no
but when i type .clear it dose not work
i mean nothing happens
do you know why ?
i guess you dont know do anyone know ?
import discord
from multiprocessing.connection import wait
from grapheme import startswith
from discord.ext import commands
import random
token = "token"
client = commands.Bot(command_prefix = '.')
@client.command()
async def clear(ctx, amount=10):
await ctx.channel.purge(limit=amount)
client.run(token)```
learn basic first
so this is correct ?
ya
someone help plz?
thanks but when i use this in a longer code it dose not work
`import discord
from multiprocessing.connection import wait
from grapheme import startswith
from discord.ext import commands
import random
token = "Token"
client = discord.Client()
client = commands.Bot(command_prefix = '.')
@client.command()
async def clear(ctx, amount=10):
await ctx.channel.purge(limit=amount)
@client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
@client.command()
async def ping(ctx):
await ctx.send(f'{round(client.latency * 1000)}')
@client.command(aliases=['8ball', 'test'])
async def _8ball(ctx, *, question):
responses = ['yes', 'no']
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
@client.event
async def on_member_join(member):
print(f'{member} has joined the server !')
@client.event
async def on_member_remove(member):
print(f'{member} has left the server !')
@client.event
async def on_message(msg):
if msg.author != client.user:
if msg.content.lower().startswith("hello"):
await msg.channel.send(f"Hi {msg.author.display_name}")
client.run(token)`
like this
remove the client = discord.Client()
it still dose not work
i removed it
what's the error?
there is no error
it just dose not work
it dose not answer to me when i type .clear for example
or even when i type .ping it dose not work
ok sure but can you help me on this please
i put my token
i just dont want to show it here 😅
i dont have any idea why it dose not work
try to remove your on_message
what should i type except that
Try putting ```await client.process_commands(msg)
```py
@client.event
async def on_message(msg):
if msg.author != client.user:
if msg.content.lower().startswith("hello"):
await msg.channel.send(f"Hi {msg.author.display_name}")
await client.process_commands(msg)
if that doesent work try changing the "client" in await client.process_commands(msg) into bot: await bot.process_commands(msg)
I want to make a command that shows all members with a timeout
i tried this code:
timed_out_members = [member for member in ctx.guild.members if member.is_timed_out()]
await ctx.send(embed = discord.Embed(description = f"{timed_out_members}"))
but this code return me this list:
[<Member id=122323131231 name='PLATINADS' discriminator='5645' bot=False nick=None guild=<Guild id=131312313123 name='server' shard_id=0 chunked=True member_count=7>>]
how to get member id from that list?
Hey, i try to make a command that shares youtube videos in a embed. How can I do that?
it returns a list because you made a list comprehension, what are you expecting?
just send the link of the video, discord will put it in an embed for you
how does the !e cmd work in the python bot?
[member.id for member in ctx.guild.members if member.is_timed_out()]
!src eval
Run Python code and get the results.
thanks
and i have list like that [1234131231312]
hot to get this id without []?
'\n'.join(str(i) for i in timed_out_members)
either [str(member) for member in ...] to get the username or [member.id for member in ...] for all the ids
and yes the join
nvm
How can I use dotenv to hide tokens in GitHub? Mainly how do I reference the file in my code?
:)
you use a special file named .gitignore and add the file paths to ignore, this prevents git from pushing the files to github also rule 7
I'm doing it for my Discord Bot
I'll just ask in a help channel then
I explained 
Nice
anyone help?
and how to get type int instead of str?
!pypi aiosqlite3
is there like a documentation of how to use it or sth?
+it has no description
with the join method you can't
but nothing changes, they are always shown in the same way
i need get id every user in timed_out_members
?
!d sqlite3
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
you don't need get id coz your starting point was a list of member object so you can use that
Hunter, long time no see
Hi
@terse coyote
i will do like that:
@glad cradle until <t:1658757166:R>
but for this i need get int member id
bro you can use member.mention
mention i did
and you can use str id as well to tag someone
not for tag
can you show your full code? you have different ways to do this
you can use a for loop for example
embed = discord.Embed(...)
for member in timed_out_members:
embed.add_field(name="?", value=f"{member.mention} until <t:{int(round(member.id.timed_out_until.timestamp()))}:R>")
...
@terse coyote
you can use a single for loop
use your member object list
def config_read():
filename = "config.txt"
contents = open(filename).read()
config = eval(contents)
token = config['token']
if __name__ == "__main__":
config_read()
client.run(token, bot=False)
name 'token' is not defined
self bots are not allowed
it worked
😄
thank you so much
not a self bot can anyone help
a lot
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
basic_python_knowledge.py
basic_python_knowledge.py
? 
you gotta learn the basics before going into this 😭
also your project breaks discord ToS
whats wrong with ma script
therefore we aren't allowed to help
least thing i care now
that's you, we care about it


💀
my friend ashley
Asher
ashley anyways



noob
exactly
do you think it's a dumb idea to do a bot blitz to try and gain traction
i made a pretty neat bot in basically 2 hours yesterday and realised i could probably make one a day 
well it's not defined
how can I do slash commands with cogs?
but its there minecraft =
idk what you are talking abt , how can i define that
of course
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
scroll down a wee bit
it's there
has the new discord.py released yet
so it's the same as normal commands but with the @strange knoll_commands?
I suppose yes
but can I have both slash and normal prefix commands with the same name?
I think so yes
there's also a thing called hybrid commands
maybe not in dpy but a fork
its there in dpy as well
no
why bother adding prefix commands with the enforcement of message content soon
they will remove prefix?
# discord.py recently added full hybrid commands. They work as follows:
## Note: as I don't see a reason not to, I will present an example using a commands.Cog.
## IMPORTANT: hybrid commands only work if the signature is compatible with app commands.
# this means that all parameters must have a type annotation, even if it is just `str`.
# this also means that you must use `Transformers` not `Coverters` in these cases.
import discord
from discord.ext import commands
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot: commands.Bot = bot
@commands.hybrid_command(name="ping")
async def ping_command(self, ctx: commands.Context) -> None:
"""
This command is actually used as an app command AND a message command.
This means it is invoked with `?ping` and `/ping` (once synced, of course).
"""
await ctx.send("Hello!")
# we use ctx.send and this will handle both the message command and app command of sending.
# added note: you can check if this command is invoked as an app command by checking the `ctx.interaction` attribute.
@commands.hybrid_group(name="parent")
async def parent_command(self, ctx: commands.Context) -> None:
"""
We even have the use of parents. This will work as usual for ext.commands but will be un-invokable for app commands.
This is a discord limitation as groups are un-invokable.
"""
... # nothing we want to do in here, I guess!
@parent_command.command(name="sub")
async def sub_command(self, ctx: commands.Context, argument: str) -> None:
"""
This subcommand can now be invoked with `?parent sub <arg>` or `/parent sub <arg>` (once synced).
"""
await ctx.send(f"Hello, you sent {argument}!")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
they wont that way many bots will become unusable they are pushing that from april
bruh this dude has more comments than code
you will have to apply for special permissions to read other peoples messages with your bot... i dont think commands are a valid reason to apply
^^
if ur bot big and good enough they will prolly still approve but if ur bot under 75 server u can still use prefix
I literally have the examples in my slash command gist
umbra?
noob
i don't think it has anything to do with size
yes
i think i applied for message content for a bot with a pretty valid reason at around 700 servers and they rejected it
no i think before 75 servers everyone gets to use message content intent
well yeah
only after bot gets to big basically they are trying to make big bots switch over
import discord
from discord.ext import commands
import afk
cogs = [afk]
client = commands.Bot(command_prefix = '>',intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
@client.event
async def on_ready():
print('Bot is online')
@client.event
async def on_member_join(member):
print(f'{member} has joined the server!')
@client.event
async def on_member_left(member):
print(f'{member} has left the server')
client.run('Token')
#afk.py
import discord
from discord.ext import commands
class boi_innit(commands.Cog):
def __init__(self,client):
self.client = client
self.data = []
@commands.command()
async def afk(self, ctx, *args):
msg = ' '.join(args)
self.data.append(ctx.author.id)
self.data.append(msg)
await ctx.send("AFK has been set!")
@commands.Cog.listener()
async def on_message(self, message):
for i in range(len(self.data)):
if (f"<@{self.data[i]}>" in message.content) and (not message.author.bot):
await message.channel.send(f"<@{self.data[i]}> **AFK:afk::** {self.data[i+1]}")
return None
break
@commands.Cog.listener()
async def on_typing(self, channel, user, when):
if user.id in self.data:
self.data.index(user.id)
self.data.remove(self.data[i+1])
self.data.remove(user.id)
await channel.send(f"{user.mention} Welcome back!")
def setup(client):
client.add_cog(boi_innit(client))
the code isnt working, could someone help!?
they can probably argue that any bot under 100 servers is for personal use, but once it's above they're gonna have problems with user data protection
actually wanted to ask if its a hybrid command instead of normal command the only thing that changes is .command .hybrid_command right?
well whatever they are trying to do they arent succeeding big bots like poketwo etc still using prefix commands
only ones which shifted over are a few economy bots
it's not enforced yet
they wont enforce anytime soon i think they are pushing the date from april
yeah, its coming up next month
yes.
so i just put .hybrid_command and it automatically adds the slash commands? do I need to do something before?
I'm a beginner 🤓
same
see -> https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#hybrid-commands fr hybrid commands explanation and examples
could someone help pls?
thx
Traceback (most recent call last):
File "main.py", line 24, in <module>
client.run('token')
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/http.py", line 216, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
here
yeah that's enough to tell you sent too many API calls
so what should i do?
wait?
yup
how long as to an estimate?
hmm k
Hi people, do you know how to create a command to remove all roles from a server?
... nuke bot?
what's the reason then
A for loop
I did this but it doesn't work
@everyone is always the first role there
you can't delete that
use slicing like ctx.guild.roles[1:]
maybe you still won't be able to delete owner
I'd ask for forgiveness
technically you did not say anything wrong
i'm owner
is there any reason to not use hybrid commands?
Message command ewwie
- 🤓
whats the syntax for autocomplete

