#discord-bots
1 messages · Page 806 of 1
ik, I'm just pulling his leg
ill pull the other
Lmao
How much would you rate the difference between discord.py and disnake?? (10 means a lot of difference in code, while 1 being the lowest)
1
ouch nice
wasnt hard at all
\👍 thanks
just change name thats all

and for the timeout endpoint its just like any other
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
lol
thanks :) I will look in the documentation :)
yw
i am using pytube to search the youtube videos(for the music bot), how do i get only the videoid from the pytube search feature
(wrong channel?, should i post it on general?)
no-one's familiar with pytube?
are you trying to make a music bot
if so please don't
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
So im developing a discord bot and I'm using threading, the problem is my thread target is an async function, so i dont know how to properly pass it in as the target for my thread, can anyone help?
Here's a small code sample: ```py
async def func1(self):
...
for interval in intervals:
thread = Thread(target=self.spawn, args=(channel, interval))
threads.append(thread)
async def spawn(self, channel, interval):
...
Error:py
RuntimeWarning: coroutine 'Spawning.spawn' was never awaited
self._target(*self._args, **self._kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
I know its not really an *error*, but my task still didnt start.
does anyone have a fivem server member count code?
for personal use
🥴 not going to ad that bot everywhere
await the coro
As the error says
uhm how so
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
await function ()
but its in a thread
you still need to await it if it's a coroutine
Just started disnakepy @client.slash_command(guild_ids=[927159708169674762]) async def ping(ctx): await ctx.send('Pong!')Made this but will it take some time to register?
thread = await Thread(target=self.spawn, args=(channel, interval))
```Like this?
target = await self.spawn
.
yea upto 1 hr , or set a default guild
@slate swan ```py
Traceback (most recent call last):
await ctx.command.invoke(ctx)
await injected(*ctx.args, **ctx.kwargs)
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object method can't be used in 'await' expression
you forgot the brackets
spawn()
thread = threading.Thread(target=await self.spawn, args=(channel, interval))
TypeError: object method can't be used in 'await' expression
oh
ok 1 sec
so do i have to pass in the args normally now?
Why don't you just call the function normally, instead of using a thread?
because i need to have this running in multiple different channels at the same time
Tried this one?
no i'll try
bruh
why not use async?
wdym
use an async function instead of thread
seeing it the third time
lol
can you give me a code example?
either way if it's private or not that's still not allowed
🥴 understood it
so basically explain what you really want the bot to do?
Been looking at the tanjun examples, I was wondering what .set_type_dependency does
tanjun.Client.from_gateway_bot(bot)
.load_modules("examples.complex_component")
# Both slash commands and message commands can be automatically executed
# by a gateway bot bound client
.load_modules("examples.message_component")
.load_modules("examples.slash_component")
.add_prefix(loaded_config.prefix)
.set_prefix_getter(get_prefix)
.set_type_dependency(config.ExampleConfig, loaded_config)
.set_type_dependency(protos.DatabaseProto, database)
# Here we use client callbacks to manage the database, STOPPING can also be used to stop it.
.add_client_callback(tanjun.ClientCallbackNames.STARTING, database.connect)
can i dm you🥴 (if no just say it , dont give me a strike or something like that)
nope
i need it to send a message in multiple channels at once (it should send the message, then wait then send it again)
🥴 🥲 ok sir
why not do thispy chids=[1234567890] #a list of channel ids for i in chids: channel=bot.get_channel(i) await channel.send('msg')
chids
channelids
Well since almost noone uses hikari here, you may get a better answer in #880982021852254270
I used lightbulb as my command handler
because it supposed to send a message to each channel and wait a certain amount of time, this amount of time is different for each channel
so like it sends a message in channel 1, then waits 8 seconds, and while its waiting it sends a message in channel 2 and waits 12 seconds, after the 8 seconds are up it send a different message in channel 1, and so on
@slate swan do you know how to do so?
so try thispy chids={channelid : time} #both are int and time is in seconds and chids is a dictionary while True: for i in chids: await asyncio.sleep(chids[i]) await client.get_channel(i).send('msg')
whats the difference between time.sleep and asyncio.sleep
time.sleep will make the whole bot sleep and the bot will not respond to other commands also
while asyncio does not make the whole bot sleep and the bot will be able to respond to other commands
oh ok
\👍
imma just test it out real quick brb
\👍
do the slash commands actually mean anything or is it just discord trying to pretend it means something
it mean something
Hmm people don't really use much slash commands
yeah
nvm i'm trying to avoid doing stuff that is not 'normal' to users, since users seem to struggle with things that are 'not normal'
nya
response: awoo
theres some small bugs, but i think i can fix them, tysm for all your help
\👍 :)
wait new problem
nvm im just dumb
so basically whats happening is it runs the spawn command but then runs the wait, and it only goes to the next iteration when the wait is complete, which is not what i want @slate swan can you help?
just return maybe
oh nvm
yeah its structure wouldn't work as is, you want an iteration that executes a bunch of stuff. all i can think of is to put the await outside of the iteration. i'm no expert though but it's my best guess
actually idk
1111111 11111111
22222222 2222222
33333333 3333333
|-----||------|-----------|
6s 8s 12s
``` This is kinda how i want it to be where a ton of ones means task 1, a ton of two means task 2, etc (not for scale)
you wanted to preserve the chronology 1->2->3 but able to execute these jobs in parallel
for i in jobs
await 1
await 2
await 3
oops no
111111 111111
2222222
333333
|-----| |------| |----------|
6s 8s 12s
``` This is how its going on rn
idk but maybe need to use a generator
this is way beyond me tbh i can't figure it out
thats why i thought i should use threading
i did try
so whats the result?
error
these
what erro
sounds painful though, because if you wanted to run threads in parallel in python it becomes really error-prone due to GIL
I guess threading cannot be used for await functions
ooh i found a solution on stack overflow
https://stackoverflow.com/questions/59645272/how-do-i-pass-an-async-function-to-a-thread-target-in-python
In case you guys wanna check it out
Try doing this```py
async def func1(channel, interval): #the function we wanted to run
#do something
def triggeer_func1(channel, interval): #an alternative function to trigger the function we want to run
asyncio.run(func1(channel, interval))
thread=threading.Thread(target=trigger_func1, args=(channel, interval)) #run the alternative function
thread.start()```
ok imma test it out
how would I make a dropdown for an embed with nextcord
You can also do```py
async def func1(channel, interval): #the function we wanted to run
#do something
thread=threading.Thread(target=asyncio.run, args=(func1(channel, interval))) #run the main function
thread.start()```
it gave me a giant error
whats the error?
i'll try this
.snipe
@client.command()
@commands.has_permissions(kick_members=True)
async def globalban(ctx, user : discord.User, reason=None):
if user == None:
await ctx.reply("Please mention a user!")
else:
for guild in client.guilds:
await ctx.discord.User.send("You have been permanently global banned from SALRP!")
await guild.ban(user, reason=reason)```
\😏
im imaging the ctx.discord.User.send is not right AT ALL dont worry
i just want to send a message to the user we are banning
still giant error
do thispy await user.send('your message')
whats the error?
What’s he trying to do?
@pallid mango
ill try
its really long i'll send you the end
RuntimeError: Task <Task pending name='Task-20' coro=<Spawning.spawn() running at cb=[_run_until_complete_cb() at got Future <Future pending cb=[shield.<locals>._outer_done_callback() at attached to a different loop
Future exception was never retrieved
future: <Future finished exception=ServerDisconnectedError('Server disconnected')>
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
thank you
👀
💀
\👍
use \👍
Just a general question
Ik...
nah its good
unicode keeps dumping massive numbers and symbols it is so annoying
:>
idk how to deal with it
Ever tried ansi?
like ok 230948q3059283532052345345
jfl what i'm gonna do with the 20358239537235235 unicode
I guess I can't help with that sorry
I heard discord is adding ansi for code block
is it true or just a rumor?
It already has
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟[0;37m⣉⡥⠶⢶⣿⣿⣿⣿⣷⣆[0m⠉⠛⠿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡿[0;37m⢡⡞⠁⠀⠀⠤⠈⠿⠿⠿⠿⣿[0m[0;31m⠀⢻⣦⡈[0m⠻⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡇⠘⡁⠀[0;37m⢀⣀⣀⣀⣈⣁⣐⡒[0m[0;31m⠢⢤⡈⠛⢿⡄[0m⠻⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡇⠀[0;37m⢀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣶⣄[0m[0;31m⠉⠐⠄⡈⢀[0m⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⠇[0;37m⢠⣿⣿⣿⣿⡿⢿⣿⣿⣿⠁⢈⣿⡄[0m⠀[0;36m⢀⣀[0m⠸⣿⣿⣿⣿
⣿⣿⣿⣿⡿⠟[0;33m⣡⣶⣶⣬⣭⣥⣴[0m[0;37m⠀⣾⣿⣿⣿⣶⣾⣿⣧[0m[0;36m⠀⣼⣿⣷⣌[0m⡻⢿⣿
⣿⣿⠟[0;33m⣋⣴⣾⣿⣿⣿⣿⣿⣿⣿⡇[0m[0;37m⢿⣿⣿⣿⣿⣿⣿⡿[0m[0;36m⢸⣿⣿⣿⣿⣷[0m⠄⢻
⡏[0;33m⠰⢾⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⢂[0m[0;37m⣭⣿⣿⣿⣿⣿⠇[0m[0;36m⠘⠛⠛⢉⣉[0m⣠⣴⣾
⣿⣷⣦[0;33m⣬⣍⣉⣉⣛⣛⣉⠉[0m[0;37m⣤⣶⣾⣿⣿⣿⣿⣿⣿⡿[0m⢰⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧[0;37m⡘⣿⣿⣿⣿⣿⣿⣿⣿⡇[0m⣼⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇[0;37m⢸⣿⣿⣿⣿⣿⣿⣿⠁[0m⣿⣿⣿⣿⣿⣿⣿⣿⣿
omg that looks like fun
nice
i'd never use it for anything though idk
Doesn't work on mobiles tho
ah so bad
how does it looks at your point?
i'm sure it will work on mobile eventually
discord seems to put massive effort into stuff like this
Mhm
you on mobile too?
BTW fun fact: Mobiles still don't have support for user and message commands
oof
wdym?
The commands u get after right clicking a user/message and going to apps option
discord's "eventually" has a different definition
why is it so hard to dm a bot
it's not
like the process is i have to make a private server, add the bot to the server, then dm the bot.
if i try to copy paste the 'bot dm link' it will not work
i wish i could just copy paste a 'bot dm link'. even if i try to 'look up the bot name in dm' it doesn't seem to work
Is the ainsi support fully released?
not for mobiles
in order for the copy paste dm link to work, you need to have dmed the bot, but then, the bot cannot dm you unless it has a mutual server with you, which effectively means you'd need to have added the bot to your private server
SOMEONE HELP ME MY BRAIN IS DYING
@client.command()
async def job(ctx):
user = ctx.author
em = discord.Embed(title= "Jobs", color=discord.Color.random())
for i in jobs:
print(i)
print(jobs[i])
print(jobs[i["pay"]])
em.add_field(name = i, value="Pay: {} | XP: {}".format(jobs[i["pay"]], jobs[i["XP"]]))
await ctx.send(embed = em)```
that redirects to https://discord.com/channels/@me
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
WHY WONT THIS WORK
whats the error?
yes, and the popup should look something like this
jobs defined?
jobs = {
"Janitor": {"pay": 1500, "XP": 50, "XPneeded": 0},
"Teacher": {"pay": 0, "XP": 250, "XPneeded": 500}
}
i never get popup..
strange
try printing something after each line and see where it stops
it stops at the em.addfield()
it just says 'no text channels'
¯_(ツ)_/¯
i feel discord purposely forces so you have to do a lot of steps to dm a bot
are u in a mutual server with the bot?
have you tried printing something after em.add_field?
yeah i guess what i could do instead, is to dm every single person in every channel the bot is in, it's the fastest way for the bot to get in their dms
an _ between add and field
@quick gust
he already has
oh then what he sent later was different ig
ye
do u have an on_command_error event?
have you tried printing after em.add_field()???
and if I try writing a print(jobs[i["pay"]]
yeah nothing goes after it
hmmm....
@client.command()
async def job(ctx):
user = ctx.author
em = discord.Embed(title= "Jobs", color=discord.Color.random())
for i in jobs:
print(jobs[i["pay"]])
em.add_field(name = i, value="Pay: {} | XP: {}".format(jobs[i["pay"]], jobs[i["XP"]]))
await ctx.send(embed = em)
didn't print anything after I ran it in my server
try thispy try: em.add_field() #fill it except Exception as e: print(e) print(em)
Nothing printed
I don't think the problem is the em.addfield
I think it's the jobs[i["pay"]]
what is it
replace jobs[i["pay"]] with jobs[i]["pay"] lol it was a common error
lol
pwned jfl
NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
Haha
shrekt
and the thing is that no one noticed lol
lol
i guess the [i["pay"]], jobs[i["XP"] part too
idk though i mean if i was a job object containing pay and XP it would make sense
oops nvm
it would then be i["pay"] instead of jobs[i["pay"]] but still not jobs[i]["pay"]
can i use async twice under @client.command()?
How to make a bot online ;-;
what do u mean? you only define a function once
My bots not coming online
you run it
error?
printing iwll only show in terminal
Yes
@client.command()
async def job(ctx):
user = ctx.author
em = discord.Embed(title= "Jobs", color=discord.Color.random())
for job in jobs:
print(job["pay"])
em.add_field(name = job, value="Pay: {} | XP: {}".format(job["pay"], job["XP"]))
await ctx.send(embed = em)
Error
show error
do you want print statement to be in just terminal?
Wait
they have already figured out the error
hmm
@client.command()
async def job(ctx):
user = ctx.author
em = discord.Embed(title= "Jobs", color=discord.Color.random())
for job in jobs:
print(job["pay"])
em.add_field(name = job, value="Pay: {} | XP: {}".format(job["pay"], job["XP"]))
await ctx.send(embed = em)
idk just guessing
dont spoonfeed btw, they understood whats wrong so they'll do it on their own
im too noob to spoonfeed lmao
im like day 4 into coding
you should not name a variable inside a function same as the function name :')
^
where is jobs defined btw @strong vessel
no idea lol its not my code
well if its not defined then you can't get anything lol
i was replying to someone else question
i presume that jobs is either a dictionary or a list
mhm, and seems like they solved the issue already
idk i have no idea i was just guessing
It's a dict
yeah its all good
^^^
i need to learn more about dict tbh
so discord bots can mass spam by DMing every person in every server it is in?
i mean i know the welcome bots do that
i'm not trying to spam of course, but trying to see if i can DM everyone
of course, and its against the ToS if you do it with the purpose to spam them
Yes, sure
@client.event()
async def on_message_delete(message):
embed=discord.Embed(title="{} deleted a message".format(message.member.name), description="", color="Blue")
embed.add_field(name= message.content, value=f"This message has been deleted by {message.user}!")
channel=client.get_channel(919024469023002631)
await channel.send(channel, embed=embed)```
getting something about coro
.event
is it spam if i'm trying to provide a welcome message to the bot? like just one message
no need of brackets
oh
nope i dont think so
ok i can try to implement that ig
since the purpose is a welcome message, not to spam someone
no brackets for first line
no, but it would be really great if you allow servers to configure if they want to dm the message or not
yeah but it is a welcome to the bot, not to the server
Oh
sounds complex
also i don't understand why when i copy paste the bot link to add to server it is permissions=0 but ig still able to read and send messages which is more than permissions 0?
you're talking about dming a user when they first use your bot right?
@client.event
async def on_message_delete(message):
embed=discord.Embed(title="{} deleted a message".format(message.user.name), description="", color="Blue")
embed.add_field(name= message.content, value=f"This message has been deleted by {message.user}!")
channel=client.get_channel(919024469023002631)
await channel.send(channel, embed=embed)```
now its saying message has no attribute user
i meant when the server owner adds the bot it would dm all the users, but if that is too spammy i could try dm user on first use of bot
Ok yeah thats spammy
yeah i'll just do the first use thing
It means the bot's own role has no permissions ( or actually it does not get created) , if bot has any other permissions it does
ngl i might be to tired and hungover to be coding lmfao
do the first use thing, yes
That would be better, since that may be annoying
use message.author
okay
!d discord.Message.author , typehint stuff to get an idea of the object's properties
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 70, in on_message_delete embed=discord.Embed(title="{} deleted a message".format(message.author), description="", color="Blue") File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/embeds.py", line 115, in __init__ self.colour = colour File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__) TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
oh color is wrong isnt it
i have ini file with section "analogue"
[analogue]
poll: ["голосовать","poll","suggest","голос"]
if copy in
@commands.command(aliases=config['analogue']['poll'])
console writing this
nextcord.ext.commands.errors.ExtensionFailed: Extension 'modules.system' raised an error: TypeError: Aliases of a command must be a list or a tuple of strings.
how fix this ?
American vs English English 👀
both works
It should be a list, not a single string
Ik, but docs 
[config[][]]
It's because all they did is ```py
class Colour:
...
Color = Colour()
[config['analogue']['poll']]?
Well, what people do is
class Colour:
. . .
Color = Colour
Indeed
That's why the Color class isn't present in the docs
thx
Yea..
@commands.has_role("SALRP | High Staff Team","SALRP | Asst. Lead Developer","SALRP | Media Director","SALRP | Gang Management","SALRP | Business Management","SALRP | Manager Assistant","Discord Appeals Team","SALRP | Head of Support Team","Department High Command"=True)```
Huh?
okay so basically, i want the command to work if a user has any of these roles
has_any_role right?
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
so just change to commands.has_any_role
yeah
wait it says something when i hover over one of them
but it will check for only one role, so if the author has even one of the roles, it will execute the command
Remove the =True
has_role is also a thing but it checks if the author has. All the role mentioned
@commands.command(aliases=[config['analogue']['poll']])
async def __POLL(self, ctx, *, arg):
new problem, bot can't find alias. on_command_error is triggered
only __POLL working
Ignoring exception in on_message_delete Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 73, in on_message_delete await channel.send(embed=embed) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/abc.py", line 1065, in send data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request raise HTTPException(r, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embed.fields.0.name: This field is required
why does my console send this every now and then
why the config, and it takes a list
I was offered to add it to the list again
!d discord.ext.commands.Command.aliases
The list of aliases the command can be invoked under.
if it is not added back to the list, an error will appear that it is not a list or a tuple
Union[List[str], Tuple[str]] means nothing to me
@commands.command()
@commands.guild_only()
async def temprole(ctx, member:discord.Member=None, time2=None):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="Role")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
if member == None:
return await ctx.send("You have to mention the member that you want to add the role to!")
if time2 == None:
return await ctx.send("You have to type the time for which you want to give the role to the mentioned member!")
with open("data.json") as f:
data = json.load(f)
if str(member.id) in data:
return await ctx.send("hmm")
with open("data.json") as f:
data = json.load(f)
data[member.id] = {"time": time2, "role": role.mention}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
data = json.load(f)
time3 = data[str(member.id)]["time"]
temprole = int(time3[:-1]) * time_convert[time3[-1]]
await member.add_roles(role)
await ctx.send(f"Successfully added the `{role.name}` role to **{member.name}#{member.discriminator}** for {time3}")
await asyncio.sleep(temprole)
await member.remove_roles(role)
with open("data.json") as f:
data = json.load(f)
data.pop(str(member.id))
with open("data.json", "w") as f:
json.dump(data, f)
await ctx.send("done")```
this is in a mods folder
Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Mods' object has no attribute 'guild'
first arg should be self
on classes
i will try
i forget cog stuff needs to have self in it
Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'data.json'
where directory data.json ?
no clue lol
is it in the same folder as your cogs file?
bruh
create this file and repeat this
okay
you need a data.json file to open it!
what file
data.json create in bot folder
put it in my cogs folder?
nope
ok
is this right?
yep
is that all i need lmfao
maybe
`Ignoring exception in command temprole:
Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/SALRP/cogs/Mods.py", line 70, in temprole
data = json.load(f)
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/init.py", line 293, in load
return loads(fp.read(),
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/init.py", line 357, in loads
return _default_decoder.decode(s)
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/wlhmpa2qk786ddp05ahv3jjlds6d44a5-python3-3.8.12/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)`
create in data.json this
{
}
yep
youll also need to have data in there though...?
Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'
open line in code where trigger error
data[member.id] = {"time": time2, "role": role.mention}```
here
is where it drops error
@commands.command()
@commands.guild_only()
async def temprole(self, ctx, member:discord.Member=None, time2=None):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="Role")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
if member == None:
return await ctx.send("You have to mention the member that you want to add the role to!")
if time2 == None:
return await ctx.send("You have to type the time for which you want to give the role to the mentioned member!")
with open("data.json") as f:
data = json.load(f)
if str(member.id) in data:
return await ctx.send("hmm")
with open("data.json") as f:
data = json.load(f)
data[member.id] = {"time": time2, "role": role.mention}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
data = json.load(f)
time3 = data[str(member.id)]["time"]
temprole = int(time3[:-1]) * time_convert[time3[-1]]
await member.add_roles(role)
await ctx.send(f"Successfully added the `{role.name}` role to **{member.name}#{member.discriminator}** for {time3}")
await asyncio.sleep(temprole)
await member.remove_roles(role)
with open("data.json") as f:
data = json.load(f)
data.pop(str(member.id))
with open("data.json", "w") as f:
json.dump(data, f)
await ctx.send("done")```
copy in data.json
{
"time":{},
"r":{}
}
okay, done
I do everything through a translator, I can not understand everything
you're very dedicated, thank you
It's my pleasure
Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'role'
I changed role.mention to ctx.role.mention, and I got passed that part of code and now I have this error.
^
wait
is there any good discord.py tutorial
ctx gives you the author
u have already ROLE
if u need mention author
@clever field can u help?
wait
mk
https://www.pythondiscord.com/pages/guides/python-guides/discordpy/
https://discordpy.readthedocs.io/en/stable/
A learning guide for the discord.py bot framework written by members of our community.
discord.py closing in this year
better using nextcord
it's fork discord.py
ctx.author.mention
if u need mention ROLE
role.mention
ah i see, is that the guide about it which u sent?
How to delete files with python
`Ignoring exception in command temprole:
Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/SALRP/cogs/Mods.py", line 75, in temprole
data[member.id] = {"time": time2, "role": role.mention}
AttributeError: 'NoneType' object has no attribute 'mention'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'`
this is the error i get
guides similiar
os.remove()
i see ty
almost nothing has changed there, except for the names of some classes
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'
why does it show this error?
your role is none
where role ?
role = discord.utils.get(guild.roles, name="Role")```
on server have role ?
im not understanding
on the server where there is a bot, is there this role?
no
create role
all i have to do is name it "Role"?
f
yes
Yes
okay, it sent hmm
"hmm"
if str(member.id) in data:
return await ctx.send("hmm")```
Or you could create a role with it
Sorry to interrupt, but If I'm doing a loop, it's ok if I open client every time in the loop, as long as I close it, right? I have a discord bot that is working only on the first instance of an event happening, but then will not work after the second or third or later instances.
guild = ctx.guild
await guild.create_role(name="role name")
await guild.create_role(name="Role")
?
wait
wait i am so confused lol
this is a temprole command, does it matter what role i set it to?
the translator tells me some kind of nonsense, but I will try to explain
why u opened in while client start ?
it's more like a crutch, if u need optimization for bot
Is it possible to change the time-out duration of a View?
I have a loop that finds places in the US where the weather meets a condition. Then within that loop, if it's in a certain state, I set a variable to 1. If that variable is 1 (within the bigger loop), then I execute this code:
if discordnumber == 1:
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
channel = client.get_channel(channelid)
await client.wait_until_ready()
await channel.send(discordtext)
await client.close()
client.run('token')
But this only works on the first instance, not on later ones. This bot also sends a tweet, which works, so it's not a script error elsewhere.
I don't even know how to do it
there it can work for a couple more seconds
after closing
@clever field with the tutorial u shared is there any video for it
eng?
maybe glowstick can help u
Greetings,
I'm glowstik most people call me glow though and I make coding tutorials, I am pretty chill and like to have fun with the community. I make discord.py videos and sometimes document a project I'm working on! I hit 1k subscribers so lets see if I can hit 10k!
was this for me? 🙂
Darn, ok.
Well, let me ask a different way. What's the best way to set up a bot to send a message whenever something happens in the backend. Should I open the connection then use an event other than on_ready() to send it?
aaaakh
u can get channel and create message
channel = bot.get_channel(ID)
await channel.send(MESSAGE)
And that doesn't have to be within an async function?
maybe I misunderstood the message
As I know maybe
I'm probably going to do more than my bot
What kind of backend
MySQL database being updated, I'm hitting it with Python and when I get a valid result, I want to tweet it (this works always) and send a message to a discord server (this works, but only the first instance). So I tend to think it's something with my discord portion of the script
You update the database with the external python script right?
Yeah exactly, all that stuff works perfectly
And the tweeting script works perfectly, a few days ago someone asked for the discord functionality
You want to make the bot do something from the script that interacts with the db, am I correct?
so im trying to get the id of the mentioned channel in the command, and im type hinting the param "channel" to discord.TextChannel. when i use channel.id, i get the error:
Converting to "_UnionGenericAlias" failed for parameter "channel".

Yeah it's basically something like this:
- Event happens in real world
- External python script updates mysql database
- Script in question searches mysql database and has a new result
- If item hasn't previously been tweeted/sent to discord, then tweet it and send to discord via this code here: #discord-bots message
Personally I just send raw requests to discord API in such case, but there must be a better method
Usually the apps are integrated into bots
There are several ways to implement this ig
Here's a bigger example of code if it helps
try:
with connection.cursor() as cursor:
sql = "query in here"
try:
cursor.execute(sql,currentdate)
except Exception as e:
print(e)
cur = cursor.fetchall()
except:
print('sql fail')
try:
if len(cur) > 0:
for item in cur:
discordnumber = 0
if item['weather'] == 'Sun':
hash = '#Sun '
elif item['weather'] == 'Rain':
hash = '#NCAAM #CBB '
discordnumber = 1
else:
hash = '#' + item['weather'] + ' '
if item['station_id'] in masterlist:
if str(item['overtime']) == str(masterlist[item['station_id']]['overtime']):
#print('Yeah we already saw')
pass
else:
if item['temperature'] > item['dew_point']:
discordtext = (weatheralerttext)
else:
discordtext = (weatheralerttext2)
api.update_status(tweet)
if discordnumber == 1:
print('discord is 1, it got this far at least')
client = discord.Client()
print('it even recognized discort.client()')
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
channel = client.get_channel(channelid)
await client.wait_until_ready()
await channel.send(discordtext)
await client.close()
client.run('token')
else:
if item['temperature'] > item['dew_point']:
discordtext = (weatheralerttext)
else:
discordtext = (weatheralerttext2)
api.update_status(tweet)
masterstationlist[item['station_id']] = {'overtime':item['overtime']}
if discordnumber == 1:
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
channel = client.get_channel(channelid)
await client.wait_until_ready()
await channel.send(discordtext)
await client.close()
client.run('token')
??
In your case you can only rewrite everything into asynchronous application or make a raw request to discord API. You don't really need the full library as it seems
i dont understand whats "ctx" can someone explain it to me
raw request seems to be the way, do you happen to know of any good tutorials? My bot is so simple I don't want to overthink this
Could you show code and how you use the command?
Just check docs for requests lib, you don't need aiohttp as your application is not asynchronous
!pypi requests
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
i use it to to add/edit stuff inside a mongodb collection:
@commands.command()
@commands.has_permissions(administrator = True)
async def setmodlog(self, ctx, channel = Optional[discord.TextChannel]):
if channel is None:
await ctx.send('Please Specify the channel')
else:
chan_id = channel.id
print(chan_id)
res = log_chancoll.find_one({'guild_id': ctx.guild.id,
'channel_id': chan_id})
if res is None:
log_chancoll.insert_one({'guild_id': ctx.message.guild.id,
'channel_id': chan_id,
'toggle': True})
await ctx.send('ModLog has been turned on')
elif res is not None:
res = res.get('toggle')
if res == True:
await ctx.send('Modlog is already turned on')
elif res == False:
log_chancoll.update_one({'guild_id': ctx.message.guild.id}, {'$set': {'toggle': True}})
await ctx.send('Modlog has been turned on')```
Wrong typehint
You set a default value, not a typehint
async def setmodlog(self, ctx, channel: discord.TextChannel = None)```
More correct
typehint it, you are setting the default value
oh okay
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
@client.event
async def on_ready():
print("I am online")
@client.command
async def ping(ctx):
await ctx.send("Pong!")```
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
why is it not working
No brackets for command decorator
yesh i forgot
@client.command()```
@commands.command()
async def temprole(self, ctx, member: discord.Member, role, duration:int):
await member.add_roles(role)
await ctx.send(f"{member.mention} has been given the {role} role for {duration}")
await asyncio.sleep(duration)
await member.remove_roles(role)
await ctx.send(f"{member.mention} has been removed from the {role} role!")```
Same error?
Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'
yea
@pallid mango typehint role as well
wdym
@vale wing can u help
did u restart your bot?
how do i do that
role: discord.Role
just turn it off and turn on again
how do i turn it off in vs code
close your terminal, at the top right of your terminal there will be a trashcan icon
click it and run the bot again
np
hello guys, how can i make if the bot join to any server write hello
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
tyty
@commands.command()
async def temprole(self, ctx, member: discord.Member, role:discord.Role, time, duration:int):
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
duration= int(time[0]) * time_convert[time[-1]]
await member.add_roles(role)
await ctx.send(f"{member.mention} has been given the {role} role for {duration}")
await asyncio.sleep(duration)
await member.remove_roles(role)
await ctx.send(f"{member.mention} has been removed from the {role} role!")```
Traceback (most recent call last): File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke await self.prepare(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare await self._parse_arguments(ctx) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments transformed = await self.transform(ctx, param) File "/home/runner/SALRP/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: duration is a required argument that is missing.
does anyone know the issue?
.. you need to invoke the command with a duration aswell
idk how
because i dont know how
we are not that smart exen 😔
lol
i haven't even touched regex
Understandable
Regex might be difficult to figure out but it is totally a useful feature
to understand regex?
he doesnt
no
true, probably should try to learn it lol
🤣
nevermind, ill wait til tomorrow
@client.event
async def on_guild_join(guild):
general = find(lambda x: x.name == 'general', guild.text_channels)
if general and general.permissions_for(guild.me).send_messages:
await general.send('Hello {}!'.format(guild.name))
Not work but nothing error code. c from discord.utils import find
use get
Indeed
and its get(iterable, name=…)
and if i dont search the general
it returns None
@vale wing thanks man turns out the html api a million times easier and everything works now 🙂
Glad to help
@client.command()
async def temprole(ctx, member: disnake.Member, role:disnake.Role, time):
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
times = int(time[0]) * time_convert[time[-1]]
await member.add_roles(role)
await ctx.send(f"{member.mention} has been given the {role} role for {times}")
await asyncio.sleep(times)
await member.remove_roles(role)
await ctx.send(f"{member.mention} has been removed from the {role} role!")
why for the seconds i am only able to put the seconds from 1-10? if i go above that, e,g i put 25s it makes it as 2s
use regex as Exen said
idk how to use regex but im close to making it work ^^
the d.py server has a regex for this (r!tag bettertimeconverter, you'd only need to typehint time to the class and time would return the seconds you inputted e.g !temprole @Member @Role 1h -> 3600s)
Is it possible to find out who deleted the user's message? (on_message_delete)
Hey, Simone knows how can I do the mobile online status?
It’s not in the api refreshes
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
Gotta use this
Okay
@bot.command()
@commands.has_permissions(administrator=True)
async def update (ctx, member: discord.Member):
unverifiedRole = discord.utils.get(ctx.guild.roles, name="unverified")
await ctx.author.remove_roles(unverifiedRole)
verifiedRole = discord.utils.get(ctx.guild.roles, name="member")
await ctx.author.add_roles(verifiedRole)```anyone know why this doesnt work? i use it as "+update {member}" and it doesnt send anything nor update the member i mentioned
?
Nvm
^^
Does the server have a role named unverified and member ( all in lower case)
There's a method, I'll check it an brb
yeah
when can i start making discord bots? after mastering beginner/intermediate or advanced py?
Does the command get executed? Try adding print statements on each step to debug it
alrr
Intermediate knowledge with concepts like OOP and asyncio would be good
ty
if you are ready to push yourself in learning things you can start it as a beginner with basic python knowledge too
i added prints, they didnt show up
Try printing unverifiedRole and verifiedRole
Can you tell me?
i printed everything in the code, the print didnt show on the console
and no errors ^^
do you have an on_message event?
I'm unsure if it would work, and I'll need to search for it
Ok, you will search?
yep but i change it to @bot.listen()
Tried searching in dpy server. Got this https://cdn.discordapp.com/attachments/559455534965850142/755074347189927967/unknown.png
Tnx bro!
hm, it seems like the bot is unable to find those roles
ctx = commands.Context
m = SomeCommands.embeded_message()
m()
Getting this error message: TypeError: 'coroutine' object is not callable
sys:1: RuntimeWarning: coroutine 'Command.call' was never awaited
function looks like this:
embed = discord.Embed(title='productname', url="https://test.com", colour=0x87CEEB, timestamp=datetime.utcnow())
await ctx.send(embed=embed)```
why? it worked with the other command
Why do you call the function?
what is jobs here you did not define jobs
no idea, if it's for a single server, try using Guild.get_role method to get the role and adding it
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Because based on my other function i would like to sent it a message
CTX is available only when a command is invoked from discord....
not by calling it thru a function
ah thanks. what should i use instead?
Is there a way to generate a discord link to authorize bot and when user agrees some role is given?
https://mystb.in/ConsecutivePromotesCookies.python
What the code should do is reset the guild vanity url if it was changed
What does it do so far?
Bans the member and sends the log if the log channel is set
What should it do?
Set the guild vanity code to the before url code
What's ur issue?
I can't get the before-after url code
before.vanity_invite.code pretty sure this has no atr
or it does but it won't work
@commands.command(name="stats")
async def stats(self, ctx, member: discord.User, full=None):
with open("./all_user_rep.json") as inf:
data = json.load(inf)
for i in range(0,len(data)): #It doesn't exist
for x in data[i]:
print(x)
if int(x) == int(member.id):
if full == True:
print("yes")
else:
print(data[i][x])
await ctx.send(str(data[i][x]["Payment Method"])+str(data[i][x]["Discord_Name"]) + str(member.id)+str(data[i][x]["rep_amount"]))
``` how do I add a condition so that if they add "full" to the command, it runs "yes"
Is it possible to find out who deleted the user's message? (on_message_delete)
ctx.message.author
Okay , wait
It is not the one who deleted the message
nvm i got it
well if someone deletes there own message?
o i see
Only in that case
NameError: name 'ctx' is not defined
send your code
Go dm
hey guys, i want to make it so that when you input the bots token via console, it stores it in a json file for further use, how would I do this?
Is it possible to find out who deleted the user's message? (on_message_delete)
import json
Token = input("token: ")
filename = 'data.json'
with open(filename, 'w') as file_object:
json.dump(Token, file_object)```
Make a file name data.json
Change the filename then
invoke the command from discord...
Helpp
hecl
thats not how json files work, dump takes an dictionary
You can only check the latest audit entries
json.dump(dict , file)
Input in console
i mean how do i retrieve from data.json
Wait k
filename = "data.json"
with open(filename, 'r') as file_object:
data = json.load(file_object)
print(data)
What?
It seems so illegal without ‘’’
ty
Can't this be done...?
i want it so that every time i host the bot, (console) it will run that so the token doesn't have to be input
!d discord.Guild.audit_logs @slate swan this only
async for ... in audit_logs(*, limit=100, before=None, after=None, oldest_first=None, user=None, action=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
R u hosting on replit or vsc
im hosting on my pc
You can't determine who deleted user's message without audit logs
Just client.run(‘ehichsjchsicgcosgxidh’)
with open(filename, 'r') as file_object:
data = json.load(file_object)
print(data)```
Read the docs
Okay
filename = 'config.json'
with open(filename, 'w') as file_object:
json.dump(token, file_object)``` @grand hazel so like this?
@cedar smelt
https://discord.com/developers/docs/interactions/application-commands#registering-a-command
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
R u trying to login ur bot
?
.
Ikr
From console?
yes
ask them to create an env file themselve
Then just
Env > json in terms of storing token
so everytime i run the file, i want it to fetch from config.json the TOKEN they inputed last time
Token = input(“token : )
Bot/client.run(Token
Or you can even encrypt it 
Oooooo
YES
Idk what tf for but I always encrypt my tokens
Yee just do what i did
.
where do i put that
Yeah
+5 user +5 message
Kinda stupid that discord is forcing us to migrate to slash commands and they put limit to those
@grand hazel so how do i make it overwrite token = input when the token is already in config.json
I will have to scam them for message content intent 
Dude can u help him
I kinda have my own problem at #help-carrot
Yeah
@scarlet aurora so you want to store the token in json file?
i want it to overwrite the token = input when there is an existing token in config.json
If you wont use the stored token and overwrite it everytime then why are you storing it
?
the first time i run the programme, it asks me to input a token
then stores in json
everytime other time it wont ask me for input, it just uses the token in config
First, create a file config.json or whatever you would like to name them
Next, this is how you fetch the json dictionary from file
import json
with open('config.json', 'r') as f:
config = json.load(f)```
You will have the contents of json file in dictionary format in your `config` variable. You can operate with it as with any dict.
After you completed required operations, just overwrite the file with the modified dict
```py
with open('config.json', 'w') as f:
json.dump(config, f)```
Then what's this
Is it possible to copy an embed by Id and get same embed paste in other server
Can bots make these events
You can only copy embed object or convert it to dict and then transfer
Pretty sure they can
You can just send the same embed object to somewhere?
You mean how to get it from a message right?
Any bot their for it
Yes by message id
@vale wing i made it so that it stores it in config.json but i don't understand how to make it so that it wont ask me for input next time
!d discord.Message.embeds just get the first element
A list of embeds the message has.
Simple if condition. Like
if config['token'] != '':
...```
Or check the len
So now to do
do i do this before the input or after
Why not check docs
Before, as you want to check if there's already a token
NameError: name 'config' is not defined```
You didn't understand it seems 🙁
😦
Have you figured it out?
i did create the config.json file
and i made it so that it stores the input in there
First you need to fetch file's content
what other i can use than ctx to just sent a message
The message itself?
with open('config.json', 'w') as f:
json.dump(config, f)
if config['token'] != '':
...```
It has most of the attributes context has
so like this?
I would like to sent embded message by just calling it from a function
This is saving file, you need to load it first
with open('config.json', 'r') as f:
config = json.load(f)
if config['token'] != '':
...```
so like this?
Well, you can use msg.channel.send
Yeah
Make sure there's a "token" key in your json file
it just has "" in json file
Fill it in
{
"token": ""
}```
oh ok
so how do i make it so that the if statement goes past the input option if config.json = token
should i put the input into a function and only call it when there is no token in config?
or is there an easier way
Yeah you can make a function if you want
async def embeded_message(msg):
embed = discord.Embed(title='productname', url="https://test.com", colour=0x87CEEB, timestamp=datetime.utcnow())
await msg.channel.send(embed=embed)
This should work, but I don't really get the point of providing msg as an argument
with open('config.json', 'r') as f:
config = json.load(f)
if config['token'] != '':
token = token
def token():
token = input(pyfade.Fade.Horizontal(pyfade.Colors.col, f"Input Token: "))
filename = 'config.json'
with open(filename, 'w') as file_object:
json.dump(token, file_object)``` so like this?
hi, i am making discord bot, can someone help me to fix mute problem?
https://github.com/Ghalbeyou/Discord-Botter
Ye me to XD. where can i find documentation how to use msg
Uh the variable and the function shouldn't be named the same.. may I ask what is you python knowledge level
!d discord.Message I guess
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
basic stuff
Like?
That should be enough
if, else, for and stuff
thanks that i was looking for
if someone have problem by opening config.json files,
i can explain how to fix it.
with open('config.json', 'r') as f:
config = json.load(f)
if config['token'] != '':
token = token
def inputtoken():
token = input(pyfade.Fade.Horizontal(pyfade.Colors.col, f"Input Token: "))
filename = 'config.json'
with open(filename, 'w') as file_object:
json.dump(token, file_object)``` so is this better @vale wing ?
Builitin bans can't be automatically timed
@scarlet aurora maybe check this? https://docs.python.org/3/library/json.html
its faster to type out stuff quickly, and no i disagree that discord's implementation are good, the slash commands are too slow on phone and some of them are not even out yet
I mean you can't provide time to discord and let the discord itself unban the user at certain time. You need a bot with tempban command
with open('config.json', 'r') as f:
config = json.load(f)
if config['token'] != '':
token = token
def inputtoken():
token = input(pyfade.Fade.Horizontal(pyfade.Colors.col, f"Input Token: "))
filename = 'config.json'
with open(filename, 'w') as file_object:
json.dump(token, file_object)``` can u just tell me whats wrong here @vale wing and what i need to add or remove
you trying to load your token from JSON?
token = token```

show the real code/issue, not the repo
oh THAT
I mean wtf is that lol
that was just an example, because i was asking u what the if statement should be to skip over the input if there is a token in config.json
why store token in json? store in .env file
# imports
import os
import json
def check():
if os.path.exists("../config.json"):
with open("../config.json", encoding="utf-8") as infile:
token = json.load(infile)
return token['bot_token']
i hope that fix the problem for you
the error?
Your function should return the entered token
so token = token?
@bot.command()
@has_permissions(manage_messages=True, manage_roles=True)
async def mute(ctx,user: discord.Member, reason):
perms = ctx.channel.overwrites_for(user)
await ctx.channel.set_permissions(user, send_message=not perms.send_message)
await ctx.send("muted the " + str(user.nick) + " !")```
this won't worked for me
no, this is help for @scarlet aurora
This is aids
with open('folder/file.json', 'r') as f:
data = json.load(f)
token = (data["token"])
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
thanks
send_messages=False
override the perms variable, send_messages = False
then update overwrites to be that
src/Client.py lines 53 to 56
@mute.error
async def mute_error(error, ctx):
if isinstance(error, CheckFailure):
await bot.send_message(ctx.message.channel, "Looks like you don't have the perm.")```
Outer directory?
why
my config is not in src folder
Nothing seems bad
Once again, you can't provide ban time to discord
Reading something from audit might take a while
It is better and faster to store the unban time and unban once it comes
The funny thing is timeout does and ban doesn't
That's weird as well
Discord actually had issues with mentions on mobile that's what I hated the most
nope, it works on desktop
Iterating through all the audit logs will take a while because of the ratelimit
/ban?
:^) Funny how a user and bot account uses the same api but ways to do things are different?
Need a little more context can't figure out how to use "msg" part for the command i used this bot = commands.Bot(command_prefix="!")
should create something like this for the message as well right?
@slate swan I mean how would you get an audit action that was done let's say 2 weeks ago?
Show the code
I can only think of iteration which is slow
The method of unbanning is weird
The method of unbanning aside, that will also be unreliable - seeing the amount of requests you would be making
hello guys i created an owner only command. How can i use error but the member not the owner? idk -> member u not the owner
if you try to add/remove multiple roles at the same time it gets messy
That's why you need custom ban command
You can't just use guild.audit_logs() here, because you're checking for an entry made a certain amount of time ago
Ah you mean put it into the reason
anybody? 😄
No invalid input handling
you can make a check , or use an if statement py if Context/Message.author.id == Context/Message.guild.owner_id: ... # do something else : ... #not owner
Not good as well, it is better to make custom ban command still
thanks
Not many great free hosts but AWS has a free tier
Does it turn off at all like replit?
replit and aws are worlds apart, so no
replit makes it pretty clear while you're running the keep_alive server, that it is not to be used in prod and should not be used 24/7
Basically confirms its not meant for your bot hosting needs. Keeping the server with uptimerobot is a workaround people found.
AWS is secure, aims to have minimal downtime, and has servers built with the assumption that they'll work with heavy workload.
vultr but it isn;'t free
When someone deletes a message, it says that I deleted it, but how can I make it so that if someone deletes a message, it says who deleted it?
In that case you would have to get the entry from audit logs
It includes the person who deleted this message. You would ideally check the audit logs inside the event itself
done but not right
How are you implementing it in code?
hey , is there a way to play tempfile in vc?
i just came to know abt tempfile now only, the code i made runs but voice doesnt come from the bot, but it gives no errors too
i want to pass a string as date like 2022-02-02 02:02:02 and then a reason that can contains spaces, how can i accept the date to let 1 space be in it?
any good vids on discord.py tutorial
i have something like this now, ```py
async def timeout(self, ctx, member: Member, *, until: Optional[Union[str, datetime]], duration: Optional[Union[float, timedelta]]=None, reason=None) -> None:
no, use this https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
You're taking in both the date and time, right?
@timid wagonyeah but then reason dosnt allow spaces cause i use *,
The simple way to do it would be to take date and time separately, and then use * for the rest of the reason
ah
You can later join the date and time strings
Yep
thats kinda bad
no
what makes it bad? other than you not getting spoonfeeded
The quality of the guide depends on how you utilize what is says 
not my taste
😐
bro what?
you're not gonna learn by looking at videos mainly.
*i dont want to read what it says
a big thing about programming is reading
if you're gonna just push of the reading part of programming, you should not be programming, none the less using discord.py
you'll have to read docs for tons of things
you'll keep following tutorials and using their code, but you wont get a single part they are doing.
^^
so yeah, reading is crucial to programming
plus reading helps you learn shit easier than watching videos.
in short, read or get out 
kk srry
tf
jeez thats low quality
android moment
ive never seen that error before actually.
Why when someone deletes a message, it says that I deleted it, but I did not delete it. (on_message_delete)
what?
show us your code
Someone deletes his message, and in the logs he writes like I deleted it, how to fix it?
gve us the code or we cant help.
Okay
@bot.event
async def on_message_delete(message):
guild = message.guild
async for entry in guild.audit_logs(limit=1, action=discord.AuditLogAction.message_delete):
print(f'{entry.user} did {entry.action} to {entry.target}')
channel = bot.get_channel(935160414965211179)
emb=discord.Embed(title="Удаленное сообшение", description="**__Информация:__**", color=discord.Color.from_rgb(255, 0, 0), timestamp=message.created_at)
emb.set_footer(text="© Все права защищены The Greatest", icon_url=message.author.avatar_url)
emb.add_field(name="**Участник:**", value=f"**{message.author.name} ({message.author.mention}) **", inline=False)
emb.add_field(name="**Удаленное сообщение:**", value=f"`{message.content}`", inline=False)
emb.add_field(name="**Удалил:**", value=f"{entry.user}", inline=False)
emb.add_field(name="**Канал • ID:**", value=f"**<#{message.channel.id}>** • **{message.id}** ", inline=False)
await channel.send(embed=emb)
Ah
it's saying that because it's fetching it from the audit logs
i think thats the reason it's saying you deleted it
(correct me if im wrong)
How to fix?
is there a property for someone that deletes a message?
nope, you cant
Helpp
most of the time you wont be able to get the person who deleted the message
i don't think what you want to do can be done @slate swan
you are trying to get the person who deleted the message correct?
Yes
ye unfortunately it doesn't seem like you can do that
You were just told you can't

