#discord-bots

1 messages ยท Page 477 of 1

patent ivy
#

getting a bit confused between default parameters and whatever these are

hasty iron
#

thats a default parameter

patent ivy
#

๐Ÿ‘

#

so is there a context equivalent to purge?

hasty iron
#

what

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

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
hasty iron
#

Context.channel can return a TextChannel object

hardy yew
#

@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")

slate swan
#

!paste

unkempt canyonBOT
#

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.

hardy yew
#

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")

hasty iron
#

!code

unkempt canyonBOT
#

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.

hardy yew
#

!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")

hasty iron
#

...

hardy yew
#

!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")

hasty iron
#

dude

slate swan
#

why do i see kotlin/javascript formatted strings here lmao

hasty iron
#

stop flooding

hardy yew
#

how

hasty iron
hardy yew
#
@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

patent ivy
#

or is it py await channel.purge(limit=amount)

hardy yew
#

ok

slate swan
#

await ctx.channel.purge(limit = amount)

hasty iron
patent ivy
#

no

#

I tried both

#

got it working

slate swan
#

it is so obvios

patent ivy
#

I don't know why you all expect me to understand everything

#

im 40 minutes in

hasty iron
#

because discord.py expects you to know basics of python

slate swan
#

yes

patent ivy
#

how do I write descriptions for my commands

stark bobcat
slate swan
#

did you define client or bot

stark bobcat
#

i am using cogs

patent ivy
#
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)')```
stark bobcat
slate swan
#

self.bot

hasty iron
stark bobcat
#

oh

patent ivy
#

thx

slate swan
hasty iron
#
def foo():
  """ this is a doc string """
stark bobcat
#

@slate swan so
@commands.command() async def latency(self, ctx): await self.bot.ctx.send(bot.latency)

#

smth like this?

hasty iron
#

AttributeError: 'Bot' object has no attribute 'ctx'

#

and also NameError

patent ivy
#

sorry if this is a dumb question but can you put a variable into a docstring

slate swan
patent ivy
#

I want to put the prefix into the description

hasty iron
#

then just put it?

hasty iron
#

no need for a variable

stark bobcat
#

wym

slate swan
stark bobcat
#

i get this error when i run it

hasty iron
#

lol

slate swan
#

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

surreal vault
#

@vestal cave what are the modules required for discord bot

boreal ravine
surreal vault
slate swan
#

yes

surreal vault
#

?

slate swan
#

Since dpy is discontinued I'd recommended disnake

surreal vault
#

so can somebody teach meh how to create a music bot i am new around python

slate swan
slate swan
unkempt canyonBOT
#

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)
slate swan
stark bobcat
stark bobcat
patent ivy
#

is there a way to wait a certain amount of time before deleting a mesage and still be available for more commands

slate swan
patent ivy
#

kwarg?

boreal ravine
#

keyword argument

slate swan
#

just delete_after

boreal ravine
#

no

hasty iron
boreal ravine
#

delete_after=time in the send function

hasty iron
#

the source code is literally unreadable

slate swan
#

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

boreal ravine
hasty iron
#

you dont

unkempt canyonBOT
#

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)
hasty iron
#

in any language

#

not just python

boreal ravine
#

nvm

boreal ravine
slate swan
#

yes

hasty iron
#

they always were

boreal ravine
#

o

#

I never knew lmfao

slate swan
#

can someone please help me with my problem

boreal ravine
#

yes what is it

slate swan
#

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

boreal ravine
#

owo

patent ivy
#

yes it is working. thank you everyone for helping. final thing before bed. how to make the bot "play" a string I give it?

boreal ravine
#

play?

hasty iron
#

play?

#

you mean tts?

slate swan
patent ivy
surreal vault
#

how to create our own music bot

boreal ravine
surreal vault
#

just to be safe from the copyrights

boreal ravine
patent ivy
#

no for my bot

boreal ravine
#

oh

#

!d discord.Activity

unkempt canyonBOT
#

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")
patent ivy
#

thx

boreal ravine
#

Is is possible to edit variables inside another command?

hasty iron
#

set that variable as an attribute of your Bot instance then sure

boreal ravine
#

lmfao

#

hm

hasty iron
#

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(?)

crystal cliff
#

Will all music bots, not working now? ๐Ÿค”

crystal cliff
hasty iron
#

no

#

its just an exaample

crystal cliff
#

๐Ÿ‘

lament mesa
#

it should take in self and guild

slate swan
crystal cliff
slate swan
crystal cliff
#

Lavalink?

lament mesa
#

!ytdl

unkempt canyonBOT
#

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)
hasty iron
#

it uses youtube

slate swan
hasty iron
#

and you think they allow streaming?

bitter depot
hasty iron
#

copyright laws apply to any platform

bitter depot
#

I'm afraid music bots aren't really a possibility

slate swan
#

dont they , i didnt knew

hasty iron
#
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.
slate swan
#

Hey is it possible to make a restart command for my bot or a command to stop all commands?

silk goblet
#

How can i auto download a file from a message of an other user?

hasty iron
#

!d discord.Message.attachments

unkempt canyonBOT
hasty iron
#

!d discord.Attachment.to_file

unkempt canyonBOT
#

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.
silk goblet
#

thanks

stiff nexus
#
    @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??
slate swan
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

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.
slate swan
#

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)
silk goblet
#

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

slate swan
#

Nvm

silk goblet
#

?

slate swan
#

I forgor /reactions wtfff

silk goblet
#

And how can i make an explanation for an command while others are typing something like other bots have?

novel rampart
#

:wtfff:

#

what is wrong

ashen gale
dense walrus
#

is there a Message.type of a spotify listen along invitation?

ashen gale
#

trying to get my bot to send random messages at infinite

#

does this look good?

novel rampart
hasty iron
#

games is a function

#

which is not an iterable

ashen gale
#

i defined a list called games

hasty iron
#

you're overriding it

ashen gale
#

how do i fix it then?

hasty iron
#

name the function soemthing else

ashen gale
#

such as?

hasty iron
#

_games and in @client.command pass in name='games'

ashen gale
#

...huh?

hasty iron
#

huh?

ashen gale
#

so what do i change the pass_context = true to?

hasty iron
#

just remove it, it does nothing

ashen gale
#

ah

#

so renaming the function is all i need to do?

kindred epoch
#

Ye

ashen gale
#

and once i input the command once, it will keep going?

kindred epoch
#

No

ashen gale
#

how do i keep it going?

kindred epoch
#

Use a loop

hasty iron
#

what do you mean by "keep it going"

kindred epoch
#

And sending it every 1 second is not good

ashen gale
#

i want it to send a message, wait for a random amount of time, and do it over again

kindred epoch
#

Use a while loop

ashen gale
#

how would i format it for this?

kindred epoch
#

If you know python enough then you should be able to do it without any help

ashen gale
#

sorry am kinda new to python

dim wing
#

is there an equivalent software of ffmpeg to use in linux?

#

or can i play audio without ffmpeg?

kindred epoch
#

And its not ment for people who are new to python

crude crater
#
@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

boreal ravine
#

@crude crater case_insensitive=True kwarg please lol

crude crater
#

And don't even say anything about the aliases, I tried the case_insensitive

#

Oop

#

I already knew someone would mention that lmfao

kindred epoch
hasty iron
#

("Owner", ctx.guild.owner, True), this can error when sending

#

Guild.owner can be None

#

use Guild.get_member(Guild.owner_id) instead

crude crater
#

That wont work for me

crude crater
hasty iron
#

why not?

crude crater
#

I'm pretty new to coding lol

kindred epoch
crude crater
hasty iron
#

why wont it

#

have you tried it

crude crater
#

Yes

#

And it wont work lmfao

hasty iron
#

what did you exactly try

crude crater
#

Using "py Guild.get_member(Guild.owner_id)" instead

#

whoops lmaoo

hasty iron
#

thats not how you do it

#

you need an instance of Guild

#

you can get one with ctx.guild

crude crater
#

I don't know if you saw my code but that's what I kinda did lol

hasty iron
#

read what i said

#

i said that Guild.owner can be None

#

and it can error when sending the embed

crude crater
#

So then what I do to fix it

kindred epoch
#

?

hasty iron
#

i already told you

#

man can you read

#

or are you new to that too

crude crater
#

I barely even speak English lmao

hasty iron
#

yeah sure, scroll up and read what i said

crude crater
#

It's not my first language so yeah I am kinda new to it ๐Ÿ˜

hasty iron
crude crater
#

I already said this

hasty iron
#

because you did it wrong

crude crater
#

How so?

hasty iron
#

and i already said why its wrong

full lily
crude crater
#

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?

hasty iron
#

a command won't give you one

#

!d discord.on_command_error

unkempt canyonBOT
#

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")).
hasty iron
#

there is the event's reference

#

build one based on that

upbeat otter
#

Guys, why does this not give me the ID of the server?

guildid = client.get_guild(int(ctx.guild.id))
kindred epoch
#

?

#

What are you doing

upbeat otter
kindred epoch
#

No

upbeat otter
#

then?

#

plz tell

kindred epoch
#

Your getting the guild id by the guild id

slate swan
#

๐Ÿ˜น๐Ÿ˜น

upbeat otter
#

.....................

#

im so damn dumb

#

imma go cry

kindred epoch
#

Ok

slate swan
#

issa learning process

upbeat otter
#

thanku tho

kindred epoch
#

Np

slate swan
#

my pfp would be so good if i had nitro

#

but what i wanted to ask is if u could get pycharm on linux

kindred epoch
#

Just download the Linux version of it

slate swan
#

okay cuz i high key wanna use it

kindred epoch
#

Ok

lucid ravine
#

any tips on how can i have my bot online 24/7 even without having my pc on? currently it srunning from repl.it

hasty iron
#

buy a vps

twilit adder
#

repl sucks pp

lucid ravine
#

any recommendations?

#

ok

kindred epoch
#

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

reef shell
kindred epoch
#

No

#

Ofc not

reef shell
#

Cheaper than galaxygate?

kindred epoch
#

Yes

reef shell
#

mhm

#

Nice

reef shell
kindred epoch
#

Idr but it's bad

crystal cliff
crystal cliff
reef shell
#

digital ocean is too much expensive

crystal cliff
reef shell
#

then the credit card gets blocked

rough flicker
#

can someone help me with my discord bot?

reef shell
#

just ask

crystal cliff
#

You should know about everything, @reef shell lol

crystal cliff
rough flicker
#

its a chat bot but it wont reply to multiple word commands how can i do that?

reef shell
slate nymph
#

async def print(ctx,*args)
Why is * used near args?

full lily
#

!args-kwargs

unkempt canyonBOT
#

*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

neon hazel
#

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

cyan sundial
#

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

brazen seal
#

Where i can find tutorial for make temporary mute role

storm zodiac
#

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
crystal cliff
slate swan
#

hey guys can anyone help me with my code?

crystal cliff
slate swan
#

a music bot

crystal cliff
slate swan
#

๐Ÿ’€

crystal cliff
crystal cliff
slate swan
#

i move to start?

crystal cliff
slate swan
#

'-'

outer violet
#

Would buttons work for dpy?

#

Cuz Iโ€™ve seen some posts and videos of people using buttons when they installed discord components

stiff nexus
stiff nexus
boreal ravine
#

posts from?

stiff nexus
boreal ravine
#

o

stiff nexus
slate nymph
#

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?

kindred epoch
crystal cliff
kindred epoch
slate nymph
#

discord.ext.command

#

bot basically

kindred epoch
kindred epoch
slate nymph
#

i dont know but it doesnt work

kindred epoch
#

It does not matter if you change it from discord.cleint to commands.bot, running the bot stays the same

slate nymph
#

oh

#

so whats the problem

kindred epoch
#

Idk

#

Does it send any error?

slate nymph
#

no it just doesnt load

#

like if i used to write it in a client server it used to say connected to lemontreebot

kindred epoch
#

Can you send an image of u doing it

slate nymph
#

i m not on pc

#

sorry

kindred epoch
#

What do you have in the file

#

What kind of stuff

slate nymph
#

let me login through the pc real quick

kindred epoch
#

Ok

#

And do you have an on_ready event?

slate nymph
#

nope

#

OHHH

crystal cliff
kindred epoch
#

Does it print anything when the file is loaded?

slate nymph
#

Wow you already solved my problem

#

i didnt care about onready

crystal cliff
#

You can add that, to keep_alive.py file

maiden fable
#

How to make @commands.command return a custom class?

kindred epoch
kindred epoch
crystal cliff
slate nymph
#

is onready in ext.command different from that of discord.client please tell me

kindred epoch
#

No is what I mean

stiff nexus
kindred epoch
#

I'm sure there better ways but that's the only thing I can think of rn

brazen seal
#

Where i can find tutorial for make temporary mute role

kindred epoch
maiden fable
#

Yo Sasuke

kindred epoch
#

Hi

maiden fable
#

Do you know about this?

#

How to make @commands.command return a custom class?

kindred epoch
#

Nope

maiden fable
#

Sad

kindred epoch
#

Lol

maiden fable
#

I want to add another attribute to the command but cannot do it :c

kindred epoch
#

F

stiff nexus
slate nymph
kindred epoch
#

Huh

slate nymph
#

await ....

kindred epoch
#

Yes

slate nymph
#

oh..

kindred epoch
maiden fable
#

:blobpain:

kindred epoch
#

!e
som = 1
som = som+1
print(som)

unkempt canyonBOT
#

@kindred epoch :white_check_mark: Your eval job has completed with return code 0.

2
kindred epoch
brisk helm
#
            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
kindred epoch
stiff nexus
#

ik that but how do it in the code

brisk helm
kindred epoch
stiff nexus
#

bruh

#

idk how to do itin the cmd

#

thats what i said

kindred epoch
#

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

lament mesa
maiden fable
lament mesa
#

๐Ÿ˜„

stiff nexus
rough flicker
#

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

stiff nexus
#
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})")
rough flicker
#

it shows @slate swan then ๐Ÿ‘‹ thats what the sample code runs

#

oh crud i actually pinged someone my bad-

slate swan
#
@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?
maiden fable
#

Hey @lament mesa

#
    value=cmd.custom_id,
AttributeError: 'Command' object has no attribute 'custom_id'
rough flicker
#

HELPPP

#

i was first

maiden fable
#

Calm down lemme see

rough flicker
#

i dont have anything to show ๐Ÿ˜›

rough flicker
#

im tryna do a code that allows mutliple words as the command

maiden fable
rough flicker
#

then spits out a random output from a list

stiff nexus
maiden fable
#

Don't ask me why it isn't async cz idk

stiff nexus
#

query = async quote_plus(roles.colour)

#

@maiden fable did not work

lament mesa
maiden fable
lament mesa
#

yeah

maiden fable
#

Oh ok

stiff nexus
maiden fable
#

Lemme see

maiden fable
#

I think it works, lemme fix this error

stiff nexus
#

ok

stiff nexus
maiden fable
stiff nexus
#

-_-

compact ruin
#

i have cut the irrelevant parts out to make it more simple

maiden fable
stiff nexus
#

ok

maiden fable
#

@lament mesa doesn't work

#

-_- bruhhhh

#

AttributeError: 'Command' object has no attribute 'custom_id'

lament mesa
#

Try printing the type of it

maiden fable
#

???

#

type of?

vale root
#

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?

slate swan
#

have u got it muted ๐Ÿค”

hasty iron
#

thatโ€™s the only thing i can think of that could be causing your issue

maiden fable
hasty iron
#

from what i can see in the source code theyre not sloted

maiden fable
#

:c

rough flicker
#

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

slate swan
#

how do i invoke a command in a cog class???

#

is it self.command.invoke?

maiden fable
#

ctx.invoke

#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

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...
lament mesa
pliant gulch
#

The decorator is right as well

maiden fable
#

Ah ok

rough flicker
#

so nobody can?

slate swan
storm zodiac
brazen seal
#

Where i can find tutorial for make temporary mute role

slate swan
#

hello there. i want to get requests from a fivem server with the ip. how can i do that?

vague grove
#

how can I make it so when i run a command and it runs into an error, it ignores it and keeps going?

vague grove
#

else:

#

pass?

slate swan
#

if member is None:
pass

vague grove
#

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

rough flicker
#

okay i need the help

#

can someone give me le help?

wicked atlas
#

Would love to help you, but...

#

!ytdl

unkempt canyonBOT
#

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)
lucid ravine
#

rip

rough flicker
#

okay?

#

what am i recreating?

#

._. so confused?

#

OH WAIT NOT ME

wicked atlas
#

Not you, sorry

rough flicker
#

uhm anyway for me

#

how do i send code rq?

wicked atlas
#

Should've use a reply there

reef shell
#

!code

unkempt canyonBOT
#

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.

lucid ravine
#

@wicked atlas could you maybe help me through pm?

slate swan
#

!ytdl

unkempt canyonBOT
#

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)
rough flicker
#

!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

wicked atlas
rough flicker
#

I want it to send a random greeting not print (random.choice(greeting))

#

@wicked atlas can you help me with that?

lucid ravine
#

ok thanks

wicked atlas
#

f-string values need to go between {}

reef shell
#

{random.choice(greeting)}

wicked atlas
#

!strings

unkempt canyonBOT
#

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.

rough flicker
#

OHHH

#

THANK YOU SO MUCH!

#

I TOTALLY FORGOT ABOUT THAT!

reef shell
#

๐Ÿ—ฟ

#

@wicked atlas the lib you are working on..
Does this supports dpy?

rough flicker
#

but now theres an error with the {}??

wicked atlas
reef shell
#

I mean can it be used as an exten.

#

Oh

rough flicker
#

@reef shell do you see a problem with it?

wicked atlas
#

Single quote strings can't be multiline

reef shell
wicked atlas
#

Either use a newline character, or use multiline strings

"firstline\nsecondline"
"""firstline
secondline"""
rough flicker
#

okay got it thanks

reef shell
#

also you don't need to set that pass_context attr.

#

It is by default True

rough flicker
#

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?

reef shell
#

Show your command code?

#
async def cmd_name(ctx, *, message):```
rough flicker
#

!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

reef shell
#

Do you want your bot to take input from you?

rough flicker
#

yes

#

its supposed to be a chat bot

reef shell
#

Then make another command for it

rough flicker
#

yes i know

dapper cobalt
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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**...
rough flicker
#

but i want it to reply to Im fine

#

not just fine like in this bit of code

dapper cobalt
#

You can use an API or a package.

dapper cobalt
#

I know a good one, hold on.

reef shell
#

mhm there is an ai api

dapper cobalt
reef shell
#

Or lib iirc

#

Not really ai

rough flicker
#

okay see

#

i want to be able to code it myself instead of having an api

reef shell
#

That would be a pain in the ass ngl

dapper cobalt
rough flicker
#

i know

dapper cobalt
#

When the world provides you an easy way to do something, don't try to take the hard way.

rough flicker
#

its my first bot so i wanna make it by coding the entirety of it

reef shell
#

Then read the docs first

rough flicker
#

T^T i know i know but i wanna make it myself my next bot ill use api

#

okay

reef shell
#

To have a basic knowledge

rough flicker
#

besides the point

#

how can i use multiple word inputs?

reef shell
#

@slate swan Yo bingusthinkmon

river walrus
#

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?

reef shell
#

why not fork dpy

hasty iron
#

doesnt sound too right

slate swan
#

lol

reef shell
#

wdym

slate swan
hasty iron
#

basically shit forks

#

all of them

#

are bad

river walrus
hasty iron
#

why not just use dpy as a reference

slate swan
#

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))

reef shell
river walrus
hasty iron
#

unstable?

reef shell
hasty iron
#

in what way

slate swan
reef shell
#

Shutdown too

#

Not sure bout restart

river walrus
hasty iron
#

well yes thatโ€™s normal, you arenโ€™t supposed to

river walrus
hasty iron
#

i see

#

okay well, good luck

river walrus
reef shell
#

@river walrus Which one is better iyo? dpy or djs

hasty iron
#

use whatever you like

reef shell
#

as you know both

hasty iron
#

there isnโ€™t a "better"

river walrus
#

Waaaay superior

brazen seal
#

why this command not work (I don't have any errors)

river walrus
hasty iron
#

what is your full code

brazen seal
#

Can you say more easier because my english is not good

hasty iron
#

!paste

unkempt canyonBOT
#

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.

brazen seal
#

you mean imports?

reef shell
river walrus
brazen seal
river walrus
#

Yeah you lack intents

brazen seal
wicked atlas
#

Ah, I see

slate swan
unkempt canyonBOT
#

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.
slate swan
#

Add that at the bottom of your on_message

reef shell
#

Also you should follow the naming Convention, using the name client for bots is not a good practice

river walrus
brazen seal
river walrus
#

That's how they use it mostly

brazen seal
reef shell
brazen seal
#

im still learning

river walrus
ionic wadi
#

รŒ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.

reef shell
river walrus
brazen seal
reef shell
#

They make custom help commands for example

river walrus
wicked atlas
ionic wadi
wicked atlas
ionic wadi
#
@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```
wicked atlas
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

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
ionic wadi
#

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

wicked atlas
#

You also don't need all those arguments, those are just defaults

ionic wadi
#

But I need It In an event?

#

How do I use It then?

wicked atlas
#
await message.channel.purge()
river walrus
#

So, is anyone interested in the project?

#

I can't do it all alone cause uni

#

blanket or perhaps Sherlock?

slate swan
#

can you even ask for that here?

pliant gulch
#

Why make a new library in the somewhat over saturated space of discord python api wrappers?

river walrus
river walrus
slate swan
#

afaik you cant advertise your projects in help channels at least

pliant gulch
#

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

river walrus
river walrus
pliant gulch
#

I'd rather use FastAPI here

storm zodiac
#

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())
river walrus
slate swan
#

is it possible to "whitelist" a command for bot developer? If it is please tell me how this is my code rn:

river walrus
pliant gulch
brazen seal
#

Hey i have ask

How i can make time muted?

pliant gulch
#

It recv's and dispatches

river walrus
pliant gulch
#

heartbeating and resuming is working afaik as well

#

I'll upload it to gist real quick

river walrus
pliant gulch
river walrus
#

Got it, thanks

pliant gulch
#

It was very W.I.P I already stopped developing it so

brazen seal
# river walrus Wdym

I want make the bot give role muted for example 1h and after 1h removing it from person

pliant gulch
#

You will need to prob patch or clean it up

#

bad code as well could be a lot better

brazen seal
#

i have

river walrus
river walrus
brazen seal
#

mysql and sqlite

river walrus
#

After Postgres ofc

brazen seal
#

mhm

#

where i find tutorial for this?

river walrus
#

And you'll find a good lib

wicked atlas
#

I think python comes with one actually

river walrus
#

I use Postgres myself

#

Since it's king

dull birch
#

Hbfgyhctf

wicked atlas
#

Yeah, sqlite is a bit hard to use with some things like docker

river walrus
#

Bruh

reef shell
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

river walrus
#

<@&831776746206265384>

wicked atlas
#

wrong macro ๐Ÿ˜”

plucky shoal
#

Please don't share such things here

wicked atlas
#

._.

dull birch
hasty iron
#

not so smart to nuke with a bot with your name in it

plucky shoal
reef shell
river walrus
dull birch
river walrus
stark hearth
rough flicker
#

@reef shell do you know how i can possibly use multiple inputs to run the line of code instead of just the one input

dull birch
mortal mango
#

As others have mentioned, sharing or discussing projects that are malicious is against our rules.

dull birch
#

It was just a test

mortal mango
#

Please remove that screenshot and refrain from continuing this discussion further.

reef shell
river walrus
#

It's illegal

rough flicker
#

may you please give me an example then?

dull birch
stark hearth
#

that easy

dull birch
#

Ig ill leave

mortal mango
stark hearth
dull birch
reef shell
river walrus
stark hearth
#

you dont have to leave the server

river walrus
#

Just don't ask for malicious code

rough flicker
#

thank you @reef shell

#

ima code it and ill let you know how it goes okie?

stark hearth
reef shell
#

Well i just gave you an idea

river walrus
reef shell
#

You have to implement on your own whatever the way you want it

rough flicker
#

mhm

reef shell
rough flicker
#

it didnt work though i changed out the arg,1, and stuff but no

river walrus
reef shell
#

They be like : oh yeah i have the admin perms why not nuke

river walrus
#

ikr

bitter depot
#

@reef shell @river walrus let's get back on topic please

reef shell
#

Alr

slate swan
#

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)```
#

?

river walrus
rough flicker
#

@reef shell what do i do if it didnt work?

bitter depot
reef shell
rough flicker
#

okay

#

im at a loss

safe otter
#

Hi, I just started using discord.py and was wondering how I could make a command work only on a specific channel

river walrus
safe otter
bitter depot
pliant gulch
#

For incoming webhooks does discord allow you to set localhost as endpoint url or will you need to ngrok it

slate swan
reef shell
#

use this decorator

river walrus
slate swan
river walrus
#

You don't need pass_context=True btw

#

That's automatically handled

slate swan
slate swan
river walrus
pliant gulch
full lily
#

ctx.guild.premium_subscribers returns List[Member]

dapper cobalt
#

" - ".join(member for member in ctx.guild.permium_subscribers)

full lily
#

so that's why you're seeing all that garbage in there

wicked atlas
dapper cobalt
pure totem
#

code py client.run("MY TOKEN")

kindred epoch
#

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

pure totem
kindred epoch
#

Lol np

misty stream
#
@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

jade jolt
#

wheres the song coming from

#

@misty stream

misty stream
#

youtube

jade jolt
#

!ytdl

unkempt canyonBOT
#

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)
misty stream
#

but i want it to be working with spotify and youtube

jade jolt
#

read above

hasty iron
#

neither allow streaming/downloading

jade jolt
#

yup

misty stream
#

there are tons of music bots

hasty iron
#

ok so

misty stream
#

how do they do it

jade jolt
#

breaking the TOS yeah

hasty iron
#

by breaking laws

jade jolt
#

some use noncopyright only ^

misty stream
#

huh

#

okey

#

what about spotify

#

do they allow it

hasty iron
#

no

#

no platform allows it

misty stream
#

damn

#

so no one in here made a music bot for youtube or spotify ?

hasty iron
#

i did

#

but weโ€™re not going to help with it

#

it breaks ToS

misty stream
#

oof

#

okey

#

then an other question

pure totem
#

wait does discord.py still exist and is popular? or do people use pycord now

misty stream
#

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

hasty iron
#

edit the message?

misty stream
#

and how cause i tried to find it but wasnt able to find anything

misty stream
#

yes

#

so channel : test1

kindred epoch
#

It had a lot more features than pycord

misty stream
#

to channel : test2

kindred epoch
#

By lot I mean a lot

#

And more are coming

hasty iron
#

classic shit dpy fork

kindred epoch
#

Lmao

hasty iron
unkempt canyonBOT
#

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.
misty stream
#

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

pure totem
misty stream
#
<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)

hasty iron
#

then youโ€™ll have to edit the file

misty stream
#

how would i do that

hasty iron
#

open file -> read -> regex and find location -> replace

#

uh thats the first thing that came in my head

misty stream
#

yeah but the file is hosted on a external host

hasty iron
#

the bot doesnโ€™t have access to it?

misty stream
#

not yet

#

idk how

hasty iron
#

then i have no clue

misty stream
#

rip

#

cause i need that to work then my bot is done Xd

pure totem
#

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

hasty iron
#

then upgrade it

pure totem
inland venture
#

whats the command that could make your bot avaiable in all channels?

pure totem
#
ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 
Consider using the `--user` option or check the permissions.```
inland venture
#

I want my bot to be avaiable on all channels

#

help plz

dapper cobalt
misty stream
#

okey can you connect python with a ftp server and edit files in that ftp ?

dapper cobalt
inland venture
#

I did, but wont let me unless i do a command

dapper cobalt
#

What? Can you show your code?

#

\n

pure totem
#

very sus for some reason, downloaded youtube_dl and it says error

#

youtube_dl could not be resolved

#

and youtube_dl is not accessed

dapper cobalt
#

Why are you spam sending @ everyone?

#

!ytdl @pure totem

unkempt canyonBOT
#

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)
inland venture
#

but any advice?

pure totem
inland venture
#

@dapper cobalt

slate swan
unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

for you too

covert igloo
#

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

slate swan
#

!d typing.Optional

unkempt canyonBOT
#

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...
slate swan
#

I think

inland venture
#

its on my server

#

not this server

slate swan
#

still API spamming

covert igloo
inland venture
#

:(

#

fine ill delete command

slate swan
covert igloo
#

idk how to use it

#

rn i have it as py member: discord.Member

slate swan
#
@bot.command()
async def command(ctx, arg: typing.Optional[int, discord.Member]):
#

innit

covert igloo
#

ah is that just making it so it can be an id or the member mention

slate swan
#

yes

#

if it doesn't work, idk

covert igloo
#

ok let me try it out

slate swan
#

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?

slate swan
#

list indices must be integers or slices, not str

lofty heron
#

hi, how can i check if someone has a certain role?

slate swan
#

I already wrote an essay man

slate swan
#

you?

#

well

#

I just proved you've read it

agile goblet
#

just do if role in member.roles

lofty heron
#

oop accidentally deleted

#

so like

slate swan
#

how can i check if a member has a role

if role in member.roles:

```???
lofty heron
#
@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')
slate swan
#

ok so i was correct

lofty heron
#

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

slate swan
#

can i make a discord bot keep logs of everytime a command is used and the time in a txt file

rugged tinsel
#

hey case_insensitive= True dosent work for me can any1 please help?

pliant compass
#

Is there an offical Discord.py way to add buttons to a bot?

slate swan
#

No

#

i didn't see you said official

pliant compass
#

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.

heavy folio
#

theres no free hosts which are good

trim barn
#
    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

heavy folio
#

@slate swan

#

@slate swan

wicked atlas
heavy folio
#

kinda forgot

#

!d discord.Guild.get_role

unkempt canyonBOT
trim barn
pliant compass
wicked atlas
#

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

wicked atlas
#

case_insensitive goes the the bot's definition, not the commands

#
bot = commands.Bot(case_insensitive=True)