#discord-bots
1 messages ยท Page 477 of 1
thats a default parameter
await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting botโs messages
Context.channel can return a TextChannel object
@client.command(pass_context=True)
async def bet(ctx,amt):
mention = await client.fetch_user(854625596184330260) #yea thats how to fetch user
st = client.get_user(512204040864661516)
await ctx.send(embed=discord.Embed(title="Matches betting rate will be based on bet365", description= " tottenham vs chelsea"))
await ctx.send(embed=discord.Embed(title="Please choose (word)", description= "1.)win \n2.)draw\n3.)lose"))
users = await getbank()
await openacc(ctx.guild.id,member.id)
try:
if int(amt) > 0:
users[f"{ctx.guild.id}.{member.id}"] -= int(amt)
with open("bank.json","w") as f:
!d sicord. json.dump(users,f)
reply = await client.wait_for('message',timeout =60)
if reply.author == ctx.message.author and reply.content == "win":
await ctx.send ('Thank You')
await mention.send(f"{author}send win ${amt}" )
await st.send("EVENT TRIGGERED")
elif reply.author == ctx.message.author and reply.content == "draw":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send draw ${amt}" )
elif reply.author == ctx.message.author and reply.content == "lose":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send lose ${amt}" )
except asyncio.TimeoutError:
await ctx.send("TIMEOUT")
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.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.
help why it cannot fetch
!paste @client.command(pass_context=True)
async def bet(ctx,amt):
mention = await client.fetch_user(854625596184330260) #yea thats how to fetch user
st = client.get_user(512204040864661516)
await ctx.send(embed=discord.Embed(title="Matches betting rate will be based on bet365", description= " tottenham vs chelsea"))
await ctx.send(embed=discord.Embed(title="Please choose (word)", description= "1.)win \n2.)draw\n3.)lose"))
users = await getbank()
await openacc(ctx.guild.id,member.id)
try:
if int(amt) > 0:
users[f"{ctx.guild.id}.{member.id}"] -= int(amt)
with open("bank.json","w") as f:
json.dump(users,f)
reply = await client.wait_for('message',timeout =60)
if reply.author == ctx.message.author and reply.content == "win":
await ctx.send ('Thank You')
await mention.send(f"{author}send win ${amt}" )
await st.send("EVENT TRIGGERED")
elif reply.author == ctx.message.author and reply.content == "draw":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send draw ${amt}" )
elif reply.author == ctx.message.author and reply.content == "lose":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send lose ${amt}" )
except asyncio.TimeoutError:
await ctx.send("TIMEOUT")
!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.
!code V
!code @client.command(pass_context=True)
async def bet(ctx,amt):
mention = await client.fetch_user(854625596184330260) #yea thats how to fetch user
st = client.get_user(512204040864661516)
await ctx.send(embed=discord.Embed(title="Matches betting rate will be based on bet365", description= " tottenham vs chelsea"))
await ctx.send(embed=discord.Embed(title="Please choose (word)", description= "1.)win \n2.)draw\n3.)lose"))
users = await getbank()
await openacc(ctx.guild.id,member.id)
try:
if int(amt) > 0:
users[f"{ctx.guild.id}.{member.id}"] -= int(amt)
with open("bank.json","w") as f:
json.dump(users,f)
reply = await client.wait_for('message',timeout =60)
if reply.author == ctx.message.author and reply.content == "win":
await ctx.send ('Thank You')
await mention.send(f"{author}send win ${amt}" )
await st.send("EVENT TRIGGERED")
elif reply.author == ctx.message.author and reply.content == "draw":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send draw ${amt}" )
elif reply.author == ctx.message.author and reply.content == "lose":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send lose ${amt}" )
except asyncio.TimeoutError:
await ctx.send("TIMEOUT")
...
!code @client.command(pass_context=True)
async def bet(ctx,amt):
mention = await client.fetch_user(854625596184330260) #yea thats how to fetch user
st = client.get_user(512204040864661516)
await ctx.send(embed=discord.Embed(title="Matches betting rate will be based on bet365", description= " tottenham vs chelsea"))
await ctx.send(embed=discord.Embed(title="Please choose (word)", description= "1.)win \n2.)draw\n3.)lose"))
users = await getbank()
await openacc(ctx.guild.id,member.id)
try:
if int(amt) > 0:
users[f"{ctx.guild.id}.{member.id}"] -= int(amt)
with open("bank.json","w") as f:
json.dump(users,f)
reply = await client.wait_for('message',timeout =60)
if reply.author == ctx.message.author and reply.content == "win":
await ctx.send ('Thank You')
await mention.send(f"{author}send win ${amt}" )
await st.send("EVENT TRIGGERED")
elif reply.author == ctx.message.author and reply.content == "draw":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send draw ${amt}" )
elif reply.author == ctx.message.author and reply.content == "lose":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send lose ${amt}" )
except asyncio.TimeoutError:
await ctx.send("TIMEOUT")
dude
why do i see kotlin/javascript formatted strings here lmao
stop flooding
how
read
@client.command(pass_context=True)
async def bet(ctx,amt):
mention = await client.fetch_user(854625596184330260) #yea thats how to fetch user
st = client.get_user(512204040864661516)
await ctx.send(embed=discord.Embed(title="Matches betting rate will be based on bet365", description= " tottenham vs chelsea"))
await ctx.send(embed=discord.Embed(title="Please choose (word)", description= "1.)win \n2.)draw\n3.)lose"))
users = await getbank()
await openacc(ctx.guild.id,member.id)
try:
if int(amt) > 0:
users[f"{ctx.guild.id}.{member.id}"] -= int(amt)
with open("bank.json","w") as f:
json.dump(users,f)
reply = await client.wait_for('message',timeout =60)
if reply.author == ctx.message.author and reply.content == "win":
await ctx.send ('Thank You')
await mention.send(f"{author}send win ${amt}" )
await st.send("EVENT TRIGGERED")
elif reply.author == ctx.message.author and reply.content == "draw":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send draw ${amt}" )
elif reply.author == ctx.message.author and reply.content == "lose":
await st.send("EVENT TRIGGERED")
await ctx.send ('Thank You')
await mention.send(f"{author}send lose ${amt}" )
except asyncio.TimeoutError:
await ctx.send("TIMEOUT")
help
why it cannot fetch the guy to fm
can anyone help
channel = ctx.channel
await purge(channel, limit=amount)```
or is it py await channel.purge(limit=amount)
ok
await ctx.channel.purge(limit = amount)
isnt it obvious
it is so obvios
because discord.py expects you to know basics of python
how do I write descriptions for my commands
did you define client or bot
i am using cogs
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="$")
@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"Pong! {round(client.latency * 1000)}ms")
@client.command()
async def purge(ctx, amount:int=1):
channel = ctx.channel
await channel.purge(limit=amount+1)
await ctx.send(f'Deleted {amount} message(s)')```
bot
self.bot
you can use a docstring
oh
thx
then it should be ```py
@client.command(description = "this is the command description")
.
.
.
def foo():
""" this is a doc string """
@slate swan so
@commands.command() async def latency(self, ctx): await self.bot.ctx.send(bot.latency)
smth like this?
sorry if this is a dumb question but can you put a variable into a docstring
its just ctx.send , self.botwont be required
also in the message to send , it should be self.bot
why
I want to put the prefix into the description
then just put it?
use a f string
uh what
no need for a variable
wym
run your current code and you'll realise what i mean
lol
how would i use avconv with discord.FFmpegPCMAudio class? i set the executable paramater as "C:\Users\jjsav\Desktop\Discord Bot\data\usr\bin\avconv.exe" and it still wont work
@vestal cave what are the modules required for discord bot
only discord.py
yes
?
Since dpy is discontinued I'd recommended disnake
so can somebody teach meh how to create a music bot i am new around python
wrong mention
!ytdl
No
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)
u can use utils
!ytdl
hm
is there a way to wait a certain amount of time before deleting a mesage and still be available for more commands
the delete_after peramater in the send function
delete_after kwarg
kwarg?
keyword argument
just delete_after
no
thats a bad lib
delete_after=time in the send function
the source code is literally unreadable
yes
how would i use avconv with discord.FFmpegPCMAudio class? i set the executable paramater as "C:\Users\jjsav\Desktop\Discord Bot\data\usr\bin\avconv.exe" and it still wont work
I've never asked this but how are people using python supposed to make discord music bots?
you dont
!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)
nvm
so discord music bots r against tos now?
yes
they always were
can someone please help me with my problem
yes what is it
how would i use avconv with discord.FFmpegPCMAudio class? i set the executable paramater as "C:\Users\jjsav\Desktop\Discord Bot\data\usr\bin\avconv.exe" and it still wont work
owo
yes it is working. thank you everyone for helping. final thing before bed. how to make the bot "play" a string I give it?
play?
is this string a url to youtube?
how to create our own music bot
stop. tryna. do. the. !ytdl. command. on. everyone. stop.
just to be safe from the copyrights
install the VSC extension
no for my bot
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
โข [`Game`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Game "discord.Game")
โข [`Streaming`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Streaming "discord.Streaming")
thx
Is is possible to edit variables inside another command?
set that variable as an attribute of your Bot instance then sure
like this ```py
@bot.command()
async def a(ctx):
ctx.bot.a = 10
@bot.command()
async def b(ctx):
await ctx.send(ctx.bot.a)
that should work(?)
Will all music bots, not working now? ๐ค
hm
ill try it thanks
Is that a calculator? ๐ค
๐
it should take in self and guild
yes the ones using ytdl
What can be used instead of youtube api?
lavalink
Lavalink?
!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)
it can use other platforms like soundcloud and spotify as well
and you think they allow streaming?
Both of which also don't allow this
copyright laws apply to any platform
I'm afraid music bots aren't really a possibility
dont they , i didnt knew
If you want to use the bot solely to listen to Spotify music with friends, you should use the native feature instead. ... Full integration isn't possible because Spotify does not allow you to stream or download full tracks per its Terms of Service, but this is a reasonable alternative.
Hey is it possible to make a restart command for my bot or a command to stop all commands?
How can i auto download a file from a message of an other user?
!d discord.Message.attachments
A list of attachments given to a message.
!d discord.Attachment.to_file
await to_file(*, use_cached=False, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Converts the attachment into a [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").
New in version 1.3.
thanks
@property
def embed(self):
page = self.pages.current_page
e = discord.Embed(color=0xffffff)
if self.title:
e.title = self.title
e.description = page.content
if self.show_page_count:
e.set_footer(text=f"Page {page.index} of {self.pages.total}",icon_url=self.ctx.author.display_avatar)
``` how do i add the thumbnail and image??
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the thumbnail.
same with set_image
What am I doing wrong? Why do I get a 404 error?
headers={'authorization': 'Bot token'}
print(requests.put("https://discord.com/api/v9/channels/866260548714627073/messages/888437581228953610/zachisted2:868327648164724756/@me", headers=headers).text)
How can i download a file of an other person of the chat and upload it per mysql into a cloud and make it avaiable per command
Nvm
?
I forgor /reactions 
And how can i make an explanation for an command while others are typing something like other bots have?
is there a Message.type of a spotify listen along invitation?

i defined a list called games
you're overriding it
how do i fix it then?
name the function soemthing else
such as?
_games and in @client.command pass in name='games'
...huh?
huh?
so what do i change the pass_context = true to?
just remove it, it does nothing
Ye
and once i input the command once, it will keep going?
No
how do i keep it going?
Use a loop
what do you mean by "keep it going"
And sending it every 1 second is not good
i want it to send a message, wait for a random amount of time, and do it over again
Use a while loop
how would i format it for this?
If you know python enough then you should be able to do it without any help
sorry am kinda new to python
is there an equivalent software of ffmpeg to use in linux?
or can i play audio without ffmpeg?
Sorry but you need to learn more first, while loops are kinda basic level.
Discord.py is a hard library
And its not ment for people who are new to python
@bot.command(aliases=["SERVERINFO", "Serverinfo", "Serverinformation", "SERVERINFORMATION", "serverinformation"])
async def serverinfo(ctx):
embed = discord.Embed(title="Server information",
colour=ctx.guild.owner.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=ctx.guild.icon_url)
fields = [("ID", ctx.guild.id, True),
("Owner", ctx.guild.owner, True),
("Region", ctx.guild.region, True),
("Created at", ctx.guild.created_at.strftime("%m/%d/%Y %H:%M:%S"), True),
("Members", len(ctx.guild.members), True),
("Humans", len(list(filter(lambda m: not m.bot, ctx.guild.members))), True),
("Bots", len(list(filter(lambda m: m.bot, ctx.guild.members))), True),
("Text channels", len(ctx.guild.text_channels), True),
("Voice channels", len(ctx.guild.voice_channels), True),
("Categories", len(ctx.guild.categories), True),
("Roles", len(ctx.guild.roles), True),
("\u200b", "\u200b", True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed=embed)
My code doesn't give me any errors it just doesn't work
It shows up with my "help" command and when I type it, it doesn't do ANYTHING, no error, no embed, nothing
@crude crater case_insensitive=True kwarg please lol
And don't even say anything about the aliases, I tried the case_insensitive
Oop
I already knew someone would mention that lmfao
If any of the value or name is empty in the field then it won't work
("Owner", ctx.guild.owner, True), this can error when sending
Guild.owner can be None
use Guild.get_member(Guild.owner_id) instead
That wont work for me
And the field isn't empty is it?
I'm pretty new to coding lol
?
It wont
what did you exactly try
thats not how you do it
you need an instance of Guild
you can get one with ctx.guild
I don't know if you saw my code but that's what I kinda did lol
read what i said
i said that Guild.owner can be None
and it can error when sending the embed
So then what I do to fix it
?
I barely even speak English lmao
yeah sure, scroll up and read what i said
It's not my first language so yeah I am kinda new to it ๐
here it is
And then when I use this it doesn't work
I already said this
because you did it wrong
How so?
and i already said why its wrong
you're struggling because a discord bot isn't a beginner project
Yeah I know lol
I have a fully functional moderation bot, ticket bot, and utility bot though so I can get it done but I just can't figure out why this command wont work
Also, someone told me to get a error handler, what's the command in this discord to do that again?
discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
Guys, why does this not give me the ID of the server?
guildid = client.get_guild(int(ctx.guild.id))
?
What are you doing
You know ctx.guild.id is the same thing as what you're doing
what i am doing is right?
No
Your getting the guild id by the guild id
๐น๐น
Ok
issa learning process
thanku tho
Np
my pfp would be so good if i had nitro
but what i wanted to ask is if u could get pycharm on linux
Why not
Just download the Linux version of it
okay cuz i high key wanna use it
Ok
any tips on how can i have my bot online 24/7 even without having my pc on? currently it srunning from repl.it
buy a vps
repl sucks pp
I use vultr
Works perfectly
With a db hosted on it
And ik that's bad
But I have no choice
Ping always stays around 20
Vultr is free?
Cheaper than galaxygate?
Yes
Why tho
Idr but it's bad
Vultr was ๐ฉ for me, custom service werenโt very helpful. ๐ฅ
Whatโs galaxygate? Try digitalocean instead. ๐๐ผ
duh
digital ocean is too much expensive
You get a trial then, leave then rejoin lol
eh?
then the credit card gets blocked
can someone help me with my discord bot?
just ask
You should know about everything, @reef shell lol
What do, you need help with?
its a chat bot but it wont reply to multiple word commands how can i do that?
bruh if it was possible then nobody would buy their service lol
async def print(ctx,*args)
Why is * used near args?
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
โข Decorators (see !tags decorators)
โข Inheritance (overriding methods)
โข Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
โข Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
Hello. Is there any way to wait for a reaction OR a message? I want the bot to work with what it receives first (i.e. with a reaction or message), not with something definite
How do I make a list of owner ids, and make some commands owner only if the users id isn't listed in that list
Where i can find tutorial for make temporary mute role
What did you need help with
i'm getting this error
Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x7f0133663640>
async def aiohttp_session():
bot.session = aiohttp.ClientSession()
bot.loop.run_until_complete(aiohttp_session())
``` how can i fix this
Adding files, but they werenโt interested/v helpful
hey guys can anyone help me with my code?
What you trying to do?
Arenโt we all ๐คฃ
๐
Token line wrong
To groovy ๐ฅ
No
'-'
Would buttons work for dpy?
Cuz Iโve seen some posts and videos of people using buttons when they installed discord components
how do i make like this?
https://media.discordapp.net/attachments/829947392651427860/888487519501566032/unknown.png
like ?ping 5 it should send the ping cmd 5 times
make what?
the amount of posts
posts from?
like ?ping 5 it should send the ping cmd 5 times
o
yes
i was using discord.client for my bot earlier now i m using discord.command i used to use py -3 for hosting my bot locally while using client what should i do for discord.command?
Use Filezilla
I know that now ๐คฃ
What do you mean by discord.commmand
Lol
Same thing then
It does not matter if you change it from discord.cleint to commands.bot, running the bot stays the same
no it just doesnt load
like if i used to write it in a client server it used to say connected to lemontreebot
Can you send an image of u doing it
let me login through the pc real quick
You donโt need that
Does it print anything when the file is loaded?
You can add that, to keep_alive.py file
How to make @commands.command return a custom class?
It's a good practice to have that so you know when the bot is ready
True, ๐ค
Repl.it is not recommended to host a bot
You could add bot online to keep_alive.py
is onready in ext.command different from that of discord.client please tell me
Not really
No is what I mean
how do i make like this?
like ?ping 5 it should send the ping cmd 5 times
https://media.discordapp.net/attachments/829947392651427860/888487519501566032/unknown.png
Use counter variables
I'm sure there better ways but that's the only thing I can think of rn
Where i can find tutorial for make temporary mute role
And while loop
Yo Sasuke
Hi
Nope
Sad
Lol
I want to add another attribute to the command but cannot do it :c
F
like?
can i use await in bot?
Huh
await ....
Yes
oh..
Wdym like
:blobpain:
!e
som = 1
som = som+1
print(som)
@kindred epoch :white_check_mark: Your eval job has completed with return code 0.
2
Lmao
curosor.execute("SELECT member_id,exp, lvl FROM lvl WHERE guild_id = ? ORDER BY exp DESC LIMIT ? OFFSET ?", (ctx.guild.id,member_per_page,member_per_page*(current -1),))
index = member_per_page*(current-1)
wynik = curosor.fetchall()
for entry in wynik:
index += 1
member_id = entry[0]
exp = entry[1]
member = ctx.guild.get_member(member_id)
embed.description += f"**{index})** {member.mention} - {exp} xp\n"
await msg.edit(embed=embed)
try:
reaction, user = await self.client.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.emoji in emojis, timeout=60.0)
except asyncio.TimeoutError:
return await msg.clear_reactions()
else:
if reaction.emoji == "โก๏ธ":
if current > len(entry) -1:
current -= 1
current += 1
elif reaction.emoji == "โฌ
๏ธ":
if current < 1:
return
current -= 1
await msg.edit(embed=embed)``` How to do if next page is clear it will do something
@stiff nexus this is what counter variables is
ik that but how do it in the code
This is just past of the code
If you know then why are you asking how to do it in code
So you want me to make you the command?
Try something that you feel will work, if it does not then ask help for it by sending it here
@commands.command(cls=CustomCommandClass)
oh, thanks ๐
๐
no
anyone know how to create a muti-word command for a chat bot? like "I'm fine" instead of "Fine"
well you could try this?
ctx.message.author.mention
instead of all that
like my code is
@bot.command(pass_context=True)
async def Hi(ctx):
await ctx.send(f"Hi {ctx.message.author.mention}๐ ")
yeah i mean
._. yeah just- use the command i showed you right now?
i was giving you an example code
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/owner.py", line 213, in roles
query = quote_plus(roles.colour)
File "/usr/lib/python3.8/urllib/parse.py", line 867, in quote_plus
string = quote(string, safe + space, encoding, errors)
File "/usr/lib/python3.8/urllib/parse.py", line 851, in quote
return quote_from_bytes(string, safe)
File "/usr/lib/python3.8/urllib/parse.py", line 876, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: quote_from_bytes() expected bytes
@commands.command()
async def roles(self, ctx):
for roles in guild.roles:
query = quote_plus(roles.colour)
url = f'https://www.google.com/search?q={query}'
await ctx.send(f"Colour:** [`{roles.colour}`]({url})")
it shows @slate swan then ๐ thats what the sample code runs
oh crud i actually pinged someone my bad-
@bot.command(pass_context = True)
async def sd(ctx):
await ctx.send("ะฃะบะฐะถะธัะต STEAMID")
def check(m):
return m.author.id == ctx.author.id
message = await bot.wait_for("message", check = check)
await ctx.send("ะฃะบะฐะถะธัะต ะดะธัะบะพัะด id")
def check(s):
return s.author.id == ctx.author.id
message2 = await bot.wait_for("message2", check = check)
with open('test.txt', 'a', encoding="utf-8") as url_file:
url_file.write(f"{message.content} , {message2.content}")```
why my code not work?
Hey @lament mesa
value=cmd.custom_id,
AttributeError: 'Command' object has no attribute 'custom_id'
help
Calm down lemme see
i dont have anything to show ๐
Can you show the decorator
urllib is blocking
im tryna do a code that allows mutliple words as the command
@commands.command(help="Set an AI Chat Channel", cls=Command, custom_id="set_channel")
then spits out a random output from a list
but why
Command.__init__ doesn't take *args
I know, it takes in func.. So I should add func instead?
yeah
Oh ok
@maiden fable help.........?
Lemme see
sorry bro, never used urllib :c
I think it works, lemme fix this error
ok
i will be here
not talking to u 
-_-
i have cut the irrelevant parts out to make it more simple
sorry
ok
@lament mesa doesn't work
-_- bruhhhh
AttributeError: 'Command' object has no attribute 'custom_id'
Try printing the type of it
Idk is this has to do with python this has nothing to do with my bot but
im trying to listen to music with a bot and i cant hear it but others can
Why?
have u got it muted ๐ค
probably because Command has __slots__ defined(?)
thatโs the only thing i can think of that could be causing your issue
Ah, totally forgot about that.. Well for now, I am using the command name to test the command and will look into that afterwards
from what i can see in the source code theyre not sloted
:c
can i get someone who is good at coding discord bots to 1 on 1 with me and help me build mine?
its my first bot and i want help so i can understand it then i can build it better from there
await invoke(*args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
cmd
Rename the class incase of it getting shadowed, and call super().__init__(. . .) after setting the attribute
The decorator is right as well
Ah ok
so nobody can?
thanks so much!
can anyone help me in #help-carrot
Where i can find tutorial for make temporary mute role
hello there. i want to get requests from a fivem server with the ip. how can i do that?
how can I make it so when i run a command and it runs into an error, it ignores it and keeps going?
pass
like
if member is None:
pass
ah
so like, im running into a heirachy error
it cant edit people with a higher role
and it just stops the command there
music bot
nice
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)
rip
Not you, sorry
Should've use a reply there
!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.
@wicked atlas could you maybe help me through pm?
!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)
!code
greeting = ["Hello", "Hey", "Heya", "Hello, world!", "Howdy", "My creators are Deme and Carlos"]
@bot.command(pass_context=True)
async def Hi(ctx):
await ctx.send(f" (random.choice(greeting)) {ctx.message.author.mention}")
so
I don't do help through DMs
I want it to send a random greeting not print (random.choice(greeting))
@wicked atlas can you help me with that?
ok thanks
f-string values need to go between {}
{random.choice(greeting)}
!strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
It's not a dpy lib, it's standalone
@reef shell do you see a problem with it?
Single quote strings can't be multiline

Either use a newline character, or use multiline strings
"firstline\nsecondline"
"""firstline
secondline"""
okay got it thanks
oh hey @reef shell how can i use mutliple word inputs?
so instead of just saying fine i can say Im fine
and the bot will know that i want a reply?
!code
greeting = ["Hello", "Hey", "Heya", "Hello, world!", "Howdy", "My creators are Deme and Carlos"]
@bot.command(pass_context=True)
async def Hi(ctx):
await ctx.send(f"{random.choice(greeting)}{ctx.message.author.mention}")
thats what i got
Do you want your bot to take input from you?
Then make another command for it
yes i know
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
You can use an API or a package.
I know a good one, hold on.
mhm there is an ai api
That would be a pain in the ass ngl

i know
When the world provides you an easy way to do something, don't try to take the hard way.
its my first bot so i wanna make it by coding the entirety of it
Then read the docs first
To have a basic knowledge
.
@slate swan Yo bingus
So, I'm looking to create a python lib from scratch (for discord bots)
We're gonna look at djs and Sapphire's source code mostly
Is there anyone up to lend a had with the development?
why not fork dpy
djs and whatever the other thing is which is probably not python as a reference for making a python lib?
doesnt sound too right
lol
wdym
is it possible to make a restart command for my bot or a command to stop all commands? ๐ฅบ
Yeah but I mean converting the ideas (and obviously adding ours) to the python code
why not just use dpy as a reference
how do i use discord.PCMVolumeTransformer is change volume? i use discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(), volume) and it does not seem to change the volume (i am using floating point numbers (1.0 2.0))
i'm not sure but there is a module you can install which can do such things
It's called jishaku
and what does it do?
Cause dpy's cache is unstable
And I will look at dpy's source code too, just not the cache
unstable?
debug and other stuffs
in what way
oh
I heard from Favna (one of the djs devs) that if you touch the cache, it gets messy
well yes thatโs normal, you arenโt supposed to
Not supposed to happen with djs tho
Thanks
@river walrus Which one is better iyo? dpy or djs
use whatever you like
as you know both
there isnโt a "better"
djs with Sapphire framework beats most of the dpy code in terms of convinience
But dpy's command handler is superior
Waaaay superior
why this command not work (I don't have any errors)
Do you have the required intents?
what is your full code
Can you say more easier because my english is not good
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.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.
you mean imports?
Bot's intents
No, intents are like permissions for the bot
You have to define them when creating bot's instance
Yeah you lack intents
Bot have Administrator permission
Basic commands like that shouldn't require intents
Ah, I see
@brazen seal refer to this
#discord-bots message
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageโs author is a bot and doesnโt call [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Add that at the bottom of your on_message
Also you should follow the naming Convention, using the name client for bots is not a good practice
He's probably following a yt guide
so i should change all client to bot?
That's how they use it mostly
yes
if you want
im still learning
Don't, yt tutorials are super weak
Refer to the documentation itself
รs there a possibility to clear messages in an event?
Since I have an antispam but I want It to delete some messages after.
I know there is in commands, but not sure bout events.
They are super misleading imo
Yeah usually that's true
so i should change all client to bot?
They make custom help commands for example
Yes
Theres also this guide here, but this requires a little bit of knowledge to begin
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.
Thanks
Please? I got threats of getting raided within 5 minutes so really need It.
Show your code
If you have a channel object, you can use purge
@bot.listen()
async def on_message(message):
member = message.author
global author_msg_counts
author_id = message.author.id
# Get current epoch time in milliseconds
curr_time = datetime.datetime.now().timestamp() * 1000
# Make empty list for author id, if it does not exist
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
# Append the time of this message to the users list of message times
author_msg_times[author_id].append(curr_time)
# Find the beginning of our time window.
expr_time = curr_time - time_window_milliseconds
# Find message times which occurred before the start of our window
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
# Remove all the expired messages times from our list
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
# ^ note: we probably need to use a mutex here. Multiple threads
# might be trying to update this at the same time. Not sure though.
if len(author_msg_times[author_id]) > max_msg_per_window:
if message.author.id != "873611098501312532":
role = member.guild.get_role(861384357758238740)
await member.add_roles(role)
print("Persoon gemute")
await message.channel.send(f"{message.author} is gemute")
author_msg_times[message.author.id] = 0
else:
return```
!d discord.TextChannel.purge
await purge(*, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own (unless you are a user account). The [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not.
Examples
Deleting botโs messages
!code
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 140, in on_message
await purge(limit=10, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True)
NameError: name 'purge' is not defined
It's a method of text channel
You also don't need all those arguments, those are just defaults
This event gives you a message object, which contains a text channel object
await message.channel.purge()
So, is anyone interested in the project?
I can't do it all alone cause uni
blanket or perhaps Sherlock?
can you even ask for that here?
Why make a new library in the somewhat over saturated space of discord python api wrappers?
I don't believe that's against the rules
Because I want an actual functional library and not some shitty dpy wannabe fork frankly
afaik you cant advertise your projects in help channels at least
Well, setting websockets are easy you would need that for a few things. And slash commands and other interactions can be handled via an HTTP server such as fastapi
"For questions and discussions"
So I believe it should be fine
Tho I am open to any concern
I'll just use aiohttp since I heard it's the best for these stuff
I'd rather use FastAPI here
how can i fix unclosed session for aiohttp.ClientSession in a global var ?
current code
async def aiohttp_session():
bot.aiosession = aiohttp.ClientSession()
print("Making a ClientSession was successful")
bot.loop.run_until_complete(aiohttp_session())
I'll take your suggestion into consideration, thanks
is it possible to "whitelist" a command for bot developer? If it is please tell me how this is my code rn:
I think there should be a bot.owner property
I have a WIP websocket code I did a while back as well that I can send
Hey i have ask
How i can make time muted?
It recv's and dispatches
I'll give you the credit if I use it
heartbeating and resuming is working afaik as well
I'll upload it to gist real quick
Wdym
Got it, thanks
It was very W.I.P I already stopped developing it so
I want make the bot give role muted for example 1h and after 1h removing it from person
You need a database for that
i have
Still appreciate the help
Which DB?
mysql and sqlite
Sqlite is better option for discord bots
After Postgres ofc
just google sqlite python lib
And you'll find a good lib
Didn't know that, thanks
I use Postgres myself
Since it's king
Hbfgyhctf
Yeah, sqlite is a bit hard to use with some things like docker
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
<@&831776746206265384>
wrong macro ๐
Please don't share such things here
._.
So i cant show sum i made with py
not so smart to nuke with a bot with your name in it
Not things that break rules/tos
Not something malicious
I can assume an age range
How
You're nuking servers, ofc you're being malicious
it breachs the terms of services
@reef shell do you know how i can possibly use multiple inputs to run the line of code instead of just the one input
Its my own server
As others have mentioned, sharing or discussing projects that are malicious is against our rules.
It was just a test
Please remove that screenshot and refrain from continuing this discussion further.
Use as many args you want in your command fuction
It's like I shoot someone in the head and say it was a test bro
It's illegal
may you please give me an example then?
How if its my server that only had me and my friend in it
bro just delete it and move on
that easy
the project that can be used for malicious purposes is against our rules, even if you don't use it that way.
wha...
Ig ill leave the server
@bot.command()
async def my_cmd(ctx, arg1, arg2, arg3,*,argr):
#command code```
You don't need to
just delete it that simple
you dont have to leave the server
Just don't ask for malicious code
and he left
Well i just gave you an idea
Eh, for the best
You have to implement on your own whatever the way you want it
mhm
Rip hecker (nuker)
it didnt work though i changed out the arg,1, and stuff but no
Funny enough that's my name on a server but I don't nuke lol
They be like : oh yeah i have the admin perms why not nuke
ikr
@reef shell @river walrus let's get back on topic please
Yessir
Alr
guys, where should I put this await message.delete() so that the bot deletes its message and the player's message```py
@bot.command(pass_context = True, aliases = ["Sd","SD"])
async def sd(ctx):
await ctx.send("ะฃะบะฐะถะธัะต STEAMID")
def check(m):
return m.author.id == ctx.author.id
message = await bot.wait_for("message", check = check)
await ctx.send("ะฃะบะฐะถะธัะต ะะธัะบะพัะด id")
def check(s):
return s.author.id == ctx.author.id
message2 = await bot.wait_for("message", check = check)
with open('test.txt', 'a', encoding="utf-8") as url_file:
url_file.write(f"\n{message.content} | {message2.content}")
iduser = message.author.id
embed = discord.Embed (title = "ะะพั ะทะฐะฟะธัะฐะป ะฒ ะะฐะทั ะดะฐะฝะฝัั
:", description = (f"STEAMID: {message.content}\nDISCORD_ID: {message2.content}"), color = 0x206694)
embed.set_footer (text = f"ะะฒัะพั: {iduser} | From server HELLARP |")
embed.timestamp = datetime.utcnow()
await ctx.send(embed = embed)```
?
Is advertising my project (as in asking for help on it and the project isn't malicious) against the rules?
@reef shell what do i do if it didnt work?
You can't advertise, but you can ask for help (assuming it doesn't violate any rules)
Aight boss you got it
Just ask here or any available help channels, someone will help you for sure
Hi, I just started using discord.py and was wondering how I could make a command work only on a specific channel
Sorry for the ping
But I'm asking for a team to help me with a project (like become a part of the team that's developing it)
And the project does not violate any rules.
Is it ok if I continue asking for it?
if ctx.channel.id == id
Oh thanks
Recruitment isn't allowed. If you'd like to discuss this further I'd recommend contacting @novel apex as then you can give more specifics so I can be sure I'm understanding correctly
For incoming webhooks does discord allow you to set localhost as endpoint url or will you need to ngrok it
idk why but i tested it on a normal cmd on there it works but not on this one can you help me with that?
@commands.is_owner()
use this decorator
By the looks of it you're using an outdated discord.py
but the other commands work with that i tested it with this account and a alt account, my alt account couldnt use the command but this one so how is not working with that specific command tho?
Just update discord.py and try again
You don't need pass_context=True btw
That's automatically handled
ok
that fixxed it
Amazing
Answered my own question, ngrok is needed
ctx.guild.premium_subscribers returns List[Member]
" - ".join(member for member in ctx.guild.permium_subscribers)
so that's why you're seeing all that garbage in there
I might suggest doing
" - ".join(member.mention for member in ctx.guild.permium_subscribers)
He said he wants the name and tag not the mention.
code py client.run("MY TOKEN")
Read the error again
And check if you added the client secret instead of the client token
Ye
It's def that, I can see it in the error
yo thanks man i haven't coded in a while because of summer break, so i forgot where the token was mb
Lol np
@bot.command(name='play')
async def play(ctx,url):
try :
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
filename = await YTDLSource.from_url(url, loop=bot.loop)
voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename))
await ctx.send('**Now playing:** {}'.format(filename))
except:
await ctx.send("The bot is not connected to a voice channel.")
how do i put the song it wants to download in a folder called music
cause i want to make a music function but it downloads music but i want to use it without downloading songs but could not find anything about it yet
youtube
!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)
but i want it to be working with spotify and youtube
read above
neither allow streaming/downloading
yup
there are tons of music bots
ok so
how do they do it
breaking the TOS yeah
by breaking laws
some use noncopyright only ^
wait does discord.py still exist and is popular? or do people use pycord now
i have a embed on my wordpress website for twitch
and i want my discord bot to be able to change the channel inside the embed
is this possible
edit the message?
and how cause i tried to find it but wasnt able to find anything
use disnake instead
It had a lot more features than pycord
to channel : test2
classic shit dpy fork
Lmao
!d discord.Message.edit
await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
yeah but how to edit that inside my wordpress website
i want my discord bot to connect with my wordpress website
to change a embed on the website
this is the embed
hmm
<html>
<body>
<!-- Add a placeholder for the Twitch embed -->
<div id="twitch-embed"></div>
<!-- Load the Twitch embed JavaScript file -->
<script src="https://embed.twitch.tv/embed/v1.js"></script>
<!-- Create a Twitch.Embed object that will render within the "twitch-embed" element -->
<script type="text/javascript">
new Twitch.Embed("twitch-embed", {
width: 854,
height: 480,
channel: "monstercat",
// Only needed if this page is going to be embedded on other websites
parent: ["embed.example.com", "othersite.example.com"]
});
</script>
</body>
</html>
and i want to change the channel: with my discord bot
with like !change (channelname here)
then youโll have to edit the file
how would i do that
open file -> read -> regex and find location -> replace
uh thats the first thing that came in my head
yeah but the file is hosted on a external host
the bot doesnโt have access to it?
then i have no clue
so i need to upgrade my pip command and it's not working for some reason
btw just downloaded python correctly and vsc and just copy and pasting the code from replit to vsc
then upgrade it
i did but it says --user is not an option
whats the command that could make your bot avaiable in all channels?
I did if message.channel.name == 'nice-place':
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied:
Consider using the `--user` option or check the permissions.```
You can use f""" to put all of this inside a f-string and make the channel a variable.
okey can you connect python with a ftp server and edit files in that ftp ?
Give it permissions to access all channels.
I did, but wont let me unless i do a command
very sus for some reason, downloaded youtube_dl and it says error
youtube_dl could not be resolved
and youtube_dl is not accessed
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)
man bro not for even a package wow
@dapper cobalt
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
for you too
How am i able to make it so when a ban command is used, it only bans if the argument for member is either an id or mention
!d typing.Optional
typing.Optional```
Optional type.
`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:
```py
def foo(arg: int = 0) -> None:
...
``` On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example...
I think
still API spamming
how does it work
well I gotta look at that
@bot.command()
async def command(ctx, arg: typing.Optional[int, discord.Member]):
innit
ah is that just making it so it can be an id or the member mention
ok let me try it out
typing.Union @covert igloo
Commands intentionally do strict typing to ensure your code behaves consistently. In this case, your default is an int, so the library will always cast to an int and will raise a UserInputError if it gets something that isn't an int.
It is good practice to explicitly type hint what you need:
async def example_command(ctx, argument: int):
...```
Note that without any hinting, the default type for arguments is str. With hinting, you will not receive anything other than the type specified.
On the rewrite branch, it is possible to use a typing.Union to specify fallbacks if conversions fail, at which point you could use isinstance as normal:
```py
async def example_command(ctx, argument: typing.Union[int, float, str]):
if isinstance(argument, int):
... # do something
elif isinstance(argument, float):
... # do something else
else:
... # this is the str branch```
copied from GitHub of course
heyyy
response = requests.get("http://localhost:30120/players.json")
test = response.json()
@client.command()
async def status(ctx):
await ctx.send(test['endpoint'])
i get this error
list indices must be integers or slices, not str
any help??
test is a list
not a dict
ok so what should i change
?
dunno
can you print test and show me the results?
sure
list indices must be integers or slices, not str
hi, how can i check if someone has a certain role?
that does not work
I already wrote an essay man
just do if role in member.roles
how can i check if a member has a role
if role in member.roles:
```???
@client.command()
async def roletest(ctx):
guild = client.get_guild(879311327720538142)
role = guild.get_role(879529307813335051)
if role in member.roles:
await ctx.send('ofuwehiyg')
else:
await ctx.send('nope')
ok so i was correct
kek
@client.command()
async def roletest(ctx):
guild = client.get_guild(879311327720538142)
role = guild.get_role(879529307813335051)
if role in ctx.message.author.roles:
await ctx.send('you have the role')
else:
await ctx.send("you don't have the role")
kekw
can i make a discord bot keep logs of everytime a command is used and the time in a txt file
hey case_insensitive= True dosent work for me can any1 please help?
Is there an offical Discord.py way to add buttons to a bot?
pls help me
full code ?
Get some free hosting thing online or if you have a really bad old computer then just run the bot on that. I have a couple bots that run on some old 2010 laptop.
theres no free hosts which are good
vote_registered_role = client.get_guild(880888575175036998).get_role(int(880888727218556949)) # Insert guild id and role id of registration role (if applicable)
AttributeError: 'NoneType' object has no attribute 'get_role'
what
Message components were added in 2.0
do py ctx.guild.get_role(id)
kinda forgot
!d discord.Guild.get_role
get_role(role_id)```
Returns a role with the given ID.
i put it in a variable class
I can't find anything about them on https://discordpy.readthedocs.io/en/stable/
Am I looking in the wrong place?
That is looking at the latest stable release, which was 1.7.3
2.0 was never officially released, and can only be installed directly from the repository and not pypi
The docs for 2.0 are found here: https://discordpy.readthedocs.io/en/master/