#discord-bots

1 messages · Page 458 of 1

steep estuary
#

so i want than the starttiem should be equal to endtime

lament mesa
#

thats not how you use cogs

steep estuary
#

starttime = endtime

#

:/

#

then?

lament mesa
#

and you forgot to add the self parameter

steep estuary
#

oo

#

i should add self parameter in each command in the class?

slate swan
#

yes

#

that's how classes work

lament mesa
steep estuary
#
@bot.command()
    @commands.has_role("Giveaway Handler")
    async def gstart(self, ctx, Channel:discord.TextChannel, endtime):
```like this?
slate swan
#

yes

steep estuary
#

but i didn't faced any problem by that

#

i only have a problem that is the StopTime is not changing after using global

noble helm
#

yesterday i discovered the wait_for command, but does that one also check for more than one time? cause im making a quiz where dont have just one try

lament mesa
#

and like i said, use a dictionary instead of global variables

steep estuary
#

inside the function or outside?

slate swan
#

As an instance var

#

Inside your class, with self

steep estuary
#

what i should change here?

slate swan
#

So that you can access and modify it from anywhere in the class

steep estuary
#

just want to change stoptime = endtime

#

?

lament mesa
steep estuary
#

:/

#

whts that?

lament mesa
#

!e ```py
class Foo:
def foo(self):
print("Foo method")

Foo().foo()```

steep estuary
#

what my command is not working now :/

lament mesa
#

You need to initialize the class

steep estuary
#

oo

unkempt canyonBOT
#

@lament mesa :white_check_mark: Your eval job has completed with return code 0.

Foo method
steep estuary
#

self is taking a place when using command

clever wind
#

in discord py, is there a way to global variables for command groups?

slate swan
#

!e

  • Remove globals, they hurt notlikeblob
  • You can say self is like an instance of your class, where you can access any of the class items from anywhere
    This is how we define classes ```py
    class X:
    def init(self): # init method, we'll initialise our vars here
    self.a = 1
    self.b = 2
    self.c = [3, 4]
Now make a method inside class ```py
    def foo(self): # self is always passed as first parameter
        print(self.a) # I can access `a` inside class
        self.a = 100

You can also access methods into other method, like ```py
def bar(self):
self.foo() # calling other method from the same class
print(self.c)
del self.c[0] # can also modify anything

Making an instance of the class ```py
x = X() # x is called an instance of the class, you can create as many as you want
        # also our __init__ is called here only
x.foo() # calling method of the class
x.bar()
# also
x.a = 99 # modified it outside the class
print(x.a)

This is how classes work, and if you didn't know that, you should learn oop first before dpy

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 100
003 | [3, 4]
004 | 99
steep estuary
#

hmm

clever wind
slate swan
#

same cmd group means? A group command or a cog?

steep estuary
clever wind
lament mesa
slate swan
#

If they're in a class, does not matter they're normal functions or commands or groups, you can access them

steep estuary
#

i am not understanding

#

but that

slate swan
lament mesa
lament mesa
slate swan
#

Just like I defined a list in the class, self.c, similarly define a dict GWcmeisterPeepoShrug

steep estuary
#
giveaway_config = dict(stop_time=0, giveaway_channel=None, participants={}, giveaway_active=False)

k

slate swan
#

notlikeblob call dict method use json like dictionaries

steep estuary
#

aaaaaaaaaaa nothing happening 😫

lament mesa
ionic wadi
#
async def help(ctx, message=None, *, member=None):
    if message is None:
        role = discord.utils.find(lambda r: r.name == 'Saus', ctx.guild.roles)
        member=f"{ctx.author}"
        if role in member.roles:
            embed=discord.Embed(title="Hoi! Hoe kan ik je helpen?", description="Zie hieronder de algemene commands. Gebruik !help (command) voor meer info!", color=discord.Color.red())
            embed.add_field(name="**Openbare commands:**", value="", inline=True)
            embed.add_field(name="!help", value="Dit commando.", inline=True)
            embed.add_field(name="!ping", value="Ping van de bot.", inline=True)
            embed.add_field(name="!verify", value="Verifieren op de bot", inline=True)
            embed.add_field(name="**Moderatie commands**", value="", inline=True)
            embed.add_field(name="!ban (persoon) (reden)", value="Persoon bannen van de server.", inline=True)
            embed.add_field(name="!unban (persoon)", value="Iemand unbannen", inline=True)        
        else:
            embed=discord.Embed(title="Hoi! Hoe kan ik je helpen?", description="Zie hieronder de algemene commands. Gebruik !help (command) voor meer info!", color=discord.Color.darkblue())
            embed.add_field(name="!help", value="Dit commando.", inline=True)
            embed.add_field(name="!ping", value="Ping van de bot.", inline=True)
            embed.add_field(name="!verify", value="Verifieren op de bot", inline=True)

Ignoring exception in command help:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/bot.py", line 48, in help
if role in member.roles:
AttributeError: 'str' object has no attribute 'roles'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'roles'

steep estuary
#

hmm

steep estuary
noble helm
#

does client.wait_for check for more than one message before quitting waiting? because im waiting for a correct answer and not any

ionic wadi
#

of the author

#

Depends on how u made It

valid galleon
#

ok so i added a command to my bot which sends a subreddit post, but the problem is, it takes a while to send the post, as its running in an asynchronous environment. so im going to switch from praw to async praw, but will i have to change any of my code? heres what ive got(part of it is cut, obviously):

        subreddit = reddit.subreddit("memes")

        all_subs = []

        hot = subreddit.top(limit = 50)
        for submission in hot:
            all_subs.append(submission)

        random_sub = random.choice(all_subs)

        name = random_sub.title
        url = random_sub.url

        embed = discord.Embed(title = name)
        embed.set_image(url = url)

        await ctx.send(embed=embed)```
severe oar
valid galleon
valid galleon
keen talon
#

!pypi reddit

unkempt canyonBOT
lament mesa
honest ermine
#

Hi, how can I add a method as a command? I've tried @commands.command() but "ping" isn't recognised

from discord.ext import commands

class LomiBot(commands.Bot):
    def __init__(self, command_prefix, help_command=None, description=None, **options):
        super().__init__(command_prefix, help_command=help_command, description=description, **options)

    async def on_ready(self):
        print("LomiBot online")

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f"pong ({self.latency*1000} ms)")


if __name__ == "__main__":
    lomibot = LomiBot(command_prefix="-")
    lomibot.run(MY_TOKEN)
hasty iron
#

if you do that you'll have to call self.add_command inside the __init__

bitter perch
honest ermine
bitter perch
#

Adding commands via bot subclass

honest ermine
#

So, If I wanted a class, should I get the bot as an atrribute instead of a subclass?

hasty iron
#

why not add the command after instantiating the Bot subclass

stiff nexus
#

i am getting error here

ems.set_author(name=guild,icon_url=guild.icon)
```the guild has no icon
honest ermine
pale turtle
#

!d discord.Guild.icon

unkempt canyonBOT
pale turtle
#

!d discord.Guild.icon_url

unkempt canyonBOT
stiff nexus
#

in 2.0.0a bruh

honest ermine
hasty iron
#

remove self if the function is outside a class

bitter perch
#

Icon should always be available

hasty iron
#

basic oop

honest ermine
hasty iron
#

a method of what

#

vaskel told you to not do it inside the subclass

honest ermine
#

So how should I do it?

#

I mean, I know how to do this with only functions, but I wanted to do it as a class because I believe is cleaner

hasty iron
#

then use a cog

honest ermine
#

Ok, I will check that, thanks

kindred zinc
#

I have made a command to create a webhook, but it gives me this error

steep estuary
#

anyone help

#

i got my problem

kindred zinc
magic ore
#

That's not how you convert it to bytes

#

Assets have a read method (a coroutine)

steep estuary
#

this is taking the StopTime Only once it is not taking the changed value of StopTime

kindred zinc
magic ore
#

!d discord.User.avatar_url

unkempt canyonBOT
#

avatar_url```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, an asset for the default avatar is returned instead.

This is equivalent to calling [`avatar_url_as()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.avatar_url_as "discord.User.avatar_url_as") with the default parameters (i.e. webp/gif detection and a size of 1024).
kindred zinc
steep estuary
magic ore
magic ore
#

.avatar is a string

#

lol

kindred zinc
magic ore
#

I told you

steep estuary
magic ore
#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
magic ore
#

I don't remember the method name but you can change the time it loops

steep estuary
#

but how i can insert a loop in it

stiff nexus
#

can i make other to not send the message in a thread?

vale narwhal
#

Any help towards this

@bot.command()
@commands.check(simple_check)
def BinaryToDecimal(binary):
	binary1 = binary
	decimal, i, n = 0, 0, 0
	while(binary != 0):
           		dec = binary % 10
           		decimal = decimal + dec * pow(2, i)
           		binary = binary//10
           		i += 1
           		return (decimal)
           		async def binarytotext(ctx, *, args):
           			bin_data = args
           			await ctx.send("The binary value is:", bin_data)
           			str_data =' '
           			for i in range(0, len(bin_data), 7):
           			 temp_data = int(bin_data[i:i + 7])
           			 decimal_data = BinaryToDecimal(temp_data)
           			 str_data = str_data + chr(decimal_data)
           			 await ctx.send("The Binary value after string conversion is:", 
       str_data)

Recieving

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 81, in <module>
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1245, in decorator
    result = command(*args, **kwargs)(func)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1412, in decorator
    return cls(func, name=name, **attrs)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/discord/ext/commands/core.py", line 217, in __init__
    raise TypeError('Callback must be a coroutine.')
TypeError: Callback must be a coroutine.

[Program finished]

vale narwhal
#

Ah

slate swan
#

wait

vale narwhal
#

wth

#

R u replying to wrong person

#

How?

#

Did you catching the error anywhere?

#

In your bot file

#

Which commands?

#

All?

#

I mean

#

All cmds that you sent?

boreal ravine
#

@slate swan y copy code

gray acorn
#

hey does anyone know how to write in python code within discord?

#

i know you need the and but forgot the command for the colourss

boreal ravine
#

!!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.

gray acorn
#

ahh thanks

boreal ravine
#

yes the youtuber

vale narwhal
#

Don't repost pls

#

Just edit it

slate swan
#

Why? ```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(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: 'NoneType' object is not subscriptable
172.18.0.1 - - [08/Sep/2021 14:47:33] "HEAD / HTTP/1.1" 200 -
Ignoring exception in command warns:
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 "main.py", line 64, in warns
embed = discord.Embed(description = f"{member.name}, have {amount[0]} warnings.", color = 0x7cf7be)
TypeError: 'NoneType' object is not subscriptable

vale narwhal
stiff nexus
#
      if msg.author is self.bot.user:
        return
      if channel:
        await msg.delete(delay=20)
```help??? its delete the bots (its own) messages also
slate swan
# vale narwhal Pls provide more information such as your specific cmd codes
@client.command()
async def warns(ctx, member: discord.Member):
  conn = await aiosqlite3.connect("testing")
  c = await conn.cursor()
  await c.execute("SELECT amount FROM warn WHERE userid= ?", (member.id,))
  amount = await c.fetchone()
  embed = discord.Embed(description = f"{member.name}, have {amount[0]} warnings.", color = 0x7cf7be)
  embed.set_footer(text=f"{ctx.me.name} | {datetime.utcnow().strftime('%A %H:%M %Y-%m-%d (UTC)')}")
  await ctx.send(embed=embed)
stiff nexus
#

ok

vale narwhal
stiff nexus
#

not working

round quarry
#

Can I make a command that appears on the server creation date?

slate swan
#

when a guild was made?

#

!d discord.Guild.created_at

unkempt canyonBOT
spare agate
#

I created this command just to test, but when I send the message, its saying that the username is None, does anyone know why?

slate swan
spare agate
#

I also tryed as integer, but it said the same thing

slate swan
#

Then the bot isn't getting the user

spare agate
#

do you know if its possible to do the opossite? convert an username to id

cold violet
#

i get this error```Ignoring exception in on_command_error
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 654, in set_permissions
overwrite = PermissionOverwrite(**permissions)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/permissions.py", line 542, in init
raise ValueError('no permission called {0}.'.format(key))
ValueError: no permission called color.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 845, in adduser
await ctx.channel.set_permissions(user, read_messages=True, send_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, color = 0xFF0000)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 656, in set_permissions
raise InvalidArgument('Invalid permissions given to keyword arguments.')
discord.errors.InvalidArgument: Invalid permissions given to keyword arguments.

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/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 441, in on_command_error
raise error
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: Invalid permissions given to keyword arguments.```

while using this command

@bot.command()
async def adduser(ctx, *, user:discord.Member=None):
  if ctx.channel.name.startswith('ticket'):
    if user != None:
      await ctx.channel.set_permissions(user, read_messages=True, send_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, color = 0xFF0000)

      embed = discord.Embed(description = f'Successfully added {user.mention} to this Ticket.')

      await ctx.send(embed = embed)

    else:
      with open('/home/runner/EBOT/info/prefixes.json', 'r') as f:
        file = json.load(f)
      prefix = file[str(ctx.guild.id)]

      embed = discord.Embed(description = f'Try the command in the following way:\nEg. `{prefix}adduser {bot.user}`', color = 0xFF0000)

      await ctx.send(embed=embed)

  else:
    pass```
spare agate
#

try colour instead of color

#

and you put color in the permissions of the channel

#

I dont think this is possible

spare agate
cold violet
#

oh yes

#
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 654, in set_permissions
    overwrite = PermissionOverwrite(**permissions)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/permissions.py", line 542, in __init__
    raise ValueError('no permission called {0}.'.format(key))
ValueError: no permission called color.
``` this part wasnt visible in terminal
cold violet
kindred zinc
magic ore
kindred zinc
#

how should I use that in my create webhook line??

magic ore
#

you're trying to access the avatar attribute of a user/member, which is the hash of their avatar
the avatar_url property of a user/member is the Asset associated with their avatar
Assets have a read method which is a coroutine, which returns the bytes of the image the asset represents

kindred zinc
#

now it shows this

maiden fable
#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a webhook for this channel.

Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.

Changed in version 1.1: Added the `reason` keyword-only parameter.
maiden fable
#

avatar=

kindred zinc
#

I tried that and it didnt work, that was my first post

crisp pine
#

does anyone know how to steal emojis command?

primal birch
#

Oh shut

unkempt canyonBOT
#

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

primal birch
#

Thanks for telling me.

steep estuary
#

please help me

#

i want to change the seconds

#

how i can change it ?

#

anyone?

median garnet
#

second for what?

steep estuary
#

seconds

#

the seconds @task.loop take

median garnet
#

StopTime =

#

maybe

steep estuary
#

but it is taking the StopTime value when the bot go online

#

after that whenever i change the value of stoptime

#

it is not changing the value of stopwatch written there

median garnet
#

i don't know if think because im new at python

steep estuary
#

k

stuck flare
#

whats the meaning of cogs i dont quite understand it?

ionic wadi
#

embed.add_field(name=f"Waarschuwing {i} gegeven door: {admin.mention}.\n",value=f"Ivm {reason}")
AttributeError: 'NoneType' object has no attribute 'mention' (Its about admin.mention)

This should be finely working right...?

ionic wadi
ionic wadi
# stuck flare ??

Sharing data between commands is easier in cogs but thats my opinion

slate swan
unkempt canyonBOT
#

class discord.ext.commands.Cog```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
stuck flare
#

ty

ionic wadi
stuck flare
#

should i learn python oop before making a bot?

ionic wadi
ionic wadi
slate swan
ionic wadi
stuck flare
slate swan
willow vine
#

how do i get a message using message id

ionic wadi
willow vine
#

it's not a command

#

ctx is not passed

#

it's under @commands.Cog.listener()

slate swan
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

await fetch_message(id)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") from the destination.

This can only be used by bot accounts.
willow vine
#

so if i do await fetch_message(id)

#

i'll get it?

slate swan
#

yea

ionic wadi
#

Most likely yes

slate swan
#

but

#

it's a method of textchannel

#

@willow vine

#

discord TextChannel that is

#

I got to go hopefully you get it if not consider OOP!

willow vine
#

so i need to do

#

channel.fetch_message(id)?

stuck flare
#

check pins

slate swan
#

i need help, i cant clear messages with this code-
import discord
from discord.ext import commands

@client.command()
async def clear(ctx, amount = int):
    await ctx.channel.purge(limit = amount)

Please tell me how to fix it?

polar coyote
stuck flare
# slate swan i need help, i cant clear messages with this code- import discord from discord....
import asyncio
import discord
from discord.ext.commands import Bot

Client = Bot('!')


@Client.command(pass_context = True)
async def clear(ctx, number):
    mgs = [] #Empty list to put all the messages in the log
    number = int(number) #Converting the amount of messages to delete to an integer
    async for x in Client.logs_from(ctx.message.channel, limit = number):
        mgs.append(x)
    await Client.delete_messages(mgs)

Client.run(Token)```
slate swan
#

how do i set a prefix with a command

stuck flare
#

maybe watch yt?

slate swan
#

theres no case in it

#

i think

stuck flare
# slate swan how do i set a prefix with a command
custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['.']

async def determine_prefix(bot, message):
    guild = message.guild
    #Only allow custom prefixs in guild
    if guild:
        return custom_prefixes.get(guild.id, default_prefixes)
    else:
        return default_prefixes

bot = commands.Bot(command_prefix = determine_prefix, ...)
bot.run()

@commands.command()
@commands.guild_only()
async def setprefix(self, ctx, *, prefixes=""):
    #You'd obviously need to do some error checking here
    #All I'm doing here is if prefixes is not passed then
    #set it to default 
    custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
    await ctx.send("Prefixes set!")```
flat solstice
#

I don't know what's wrong with this command but i'm gettig a syntax error on the asyncpy @commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]") @commands.bot_has_permissions(manage_messages = True) @commands.has_permissions(manage_messages = True) async def massban(self, ctx, Optional[days : int] = 0, reason : str, *, targets: commands.Greedy[discord.Member]): with ctx.typing(): users = 0 for user in targets: users += 1 await ban(user, reason = reason, delete_message_days = days) await ctx.send(f"len(users) were just banned.", delete_after = 5)

polar coyote
stuck flare
hasty iron
#

json bad

stuck flare
polar coyote
slate swan
hasty iron
#

json is basically a dict if you use it as one

polar coyote
slate swan
#

when someone says the problem 10 sec ago

#

import asyncio
import discord
from discord.ext.commands import Bot

Client = Bot('!')


@Client.command(pass_context = True)
async def clear(ctx, number):
    mgs = [] #Empty list to put all the messages in the log
    number = int(number) #Converting the amount of messages to delete to an integer
    async for x in Client.logs_from(ctx.message.channel, limit = number):
        mgs.append(x)
    await Client.delete_messages(mgs)

Client.run(Token)```
slate swan
#

@slate swan

slate swan
waxen granite
#

How do i delete recent msgs in all channels by a member?

slate swan
hasty iron
#

wont work

slate swan
waxen granite
slate swan
#
client = commands.Bot(command_prefix='-')

@client.command(name='clear', help='this command will clear msgs')
async def clear(ctx, amount = 5):
    await ctx.channel.purge(limit=amount)```
waxen granite
hasty iron
#

or you could

#

iterate through every channel and delete

slate swan
hasty iron
#

TextChannel.purge has a check kwarg

slate swan
#

yea

#
@client.event
async def on_message(message):
    await message.delete()```
waxen granite
#

Well i am trying to ban/softban a member who sends msgs in almost all channels in under 10 seconds.

slate swan
#

Deletw ownpy #this code will send "HI" for 3 seconds when the user says "HI" #discord.py rewrite #python 3+ include time @bot.event async def on_message(message): #Only continue if the message is "HI" if not message.content == "HI": return #Send HI back, and set it to a var BotMessage = await ctx.send("HI") #wait 3 seconds time.sleep(3) #delete the bot's msg BotMessage.delete()

waxen granite
#

There's a lot of fake discord nitro activity now a days

hasty iron
#

stop copying code and pasting it here

#

there are 2 NameErrors infact

slate swan
#

anyone nows how to change the profile picture of a bot with a command ?

hasty iron
#

!d discord.ClientUser.edit

unkempt canyonBOT
#

await edit(**fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the current profile of the client.

If a bot account is used then a password field is optional, otherwise it is required.

Warning

The user account-only fields are deprecated...
polar coyote
slate swan
slate swan
slate swan
hasty iron
slate swan
#

how ?

#

i was searching like

hasty iron
slate swan
#

2 hours x)

polar coyote
hasty iron
stuck flare
#

@slate swan py with open('image.png', 'rb') as image: await client.user.edit(avatar=image)

polar coyote
slate swan
hasty iron
stuck flare
#

yw

slate swan
#

@stuck flare clear code you gave me is not working

hasty iron
#

you can also get an image from the internet by sending a GET request to its url using aiohttp and then calling await response.read() which returns a bytes object

willow vine
#

guys how to get message using message id without passing channel

slate swan
#
@Client.command(pass_context = True)
async def clear(ctx, number):
    mgs = [] #Empty list to put all the messages in the log
    number = int(number) #Converting the amount of messages to delete to an integer
    async for x in Client.logs_from(ctx.message.channel, limit = number):
        mgs.append(x)
    await Client.delete_messages(mgs)

Client.run(Token)```
This is not working :c
polar coyote
polar coyote
hasty iron
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
hasty iron
#

and you dont even need that

willow vine
hasty iron
#

!d discord.TextChannel.purge does what you want for you

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
willow vine
#

all i want is that particular message

#

using it's id

polar coyote
hasty iron
#

hm

willow vine
#

how do i store a message in a text file

#

i mean the whole object

#

or any file

hasty iron
willow vine
hasty iron
#

let me see

slate swan
#

that user will put

hasty iron
#

but i dont recommend using it

slate swan
#

!d discord delete

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

slate swan
#

:

#

!d discord delete-messages

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

hasty iron
hasty iron
flat solstice
#

I don't know why but this code keeps giving me indentation errors and I have unindented it all and re-indented it with no success.```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, days : Optional[int], reason : str, *, targets: commands.Greedy[discord.Member]):
users = 0
with ctx.channel.typing(): # <---- This line is giving me errors
for user in targets:
users += 1
await ban(user, reason = "Unspecified" if reason == None else reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))

        await ctx.reply(f"{len(users)} were just banned.", delete_after = 5) # <---- as is this line```
willow vine
hasty iron
#

because you're using internals

willow vine
#

what does that mean

hasty iron
#

and also it grabs from cache

#

it can return None

willow vine
#

I'm kinda noob ;-;

hasty iron
#

internals?

willow vine
#

using internals

#

and getting data from cache

hasty iron
willow vine
#

oh why aren't you supposed to

hasty iron
#

because they're private..?

willow vine
#

oh

hasty iron
#

i mean thats the convention

willow vine
#

hmm okay

hasty iron
#

if an attribute starts with _ that means its private

willow vine
#

is there a way i can store a message in a file

#

then

hasty iron
#

why in a file

#

use a database

willow vine
#

like what i basically want is, if i unload a cog, the variable will be lost, so the msg variable is gone

#

oh

#

yeah idk how to use a database yet

#

and store objects in it

hasty iron
#

learn how to then

willow vine
#

which database should i use

#

mysql?

hasty iron
#

most people recommend postgresql for sql db and for no sql its mongodb

slate swan
hasty iron
#

oh wait forgot that existed

trim kayak
#

Hi. Does anyone know what the difference between nextcord and pycord? 🧐
For the development of a totally new bot, which one of the these are recommended?

maiden fable
#

Well I haven't used either so can't suggest

trim kayak
slate swan
#

can someone tell the code for deleting the messages on the channel on which user has sent the clear command

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
flat solstice
slate swan
slate swan
#

limit can be made a command argument, and do limit=limit

#

where limit will be the int(amount) the user passes in

#

does it work?

#

yes

#

wait i will try

#

aight

#

its showing error

#

and its not workin

#

limit is not accessed as pylance

#

😦

halcyon bison
#

how tf is it on moiele

clever wind
#

class Lobby:
def init(self, lobby_number, queue_channel_id, Team_A_channel_id, Team_B_channel_id):

queue_channel = client.get_channel(queue_channel_id)
Team_A_channel = client.get_channel(Team_A_channel_id)
Team_B_channel = client.get_channel(Team_B_channel_id)

queue_channel_members = queue_channel.members
queue_channel_members_mention = []
for member in queue_channel_members:
    queue_channel_members_mention.append(member.mention)

@client.group(invoke_without_command=True)
async def lobby(ctx):
  ctx.send("Lobbies Online.")

@lobby.command()
async def start(ctx):
    random.shuffle(queue_channel_members_mention)

    team_a = queue_channel_members_mention[len(queue_channel_members_mention) // 2:]
    team_b = queue_channel_members_mention[:len(queue_channel_members_mention) // 2]

    embed_lobby1 = discord.Embed(title="Teams")
    embed_lobby1.add_field(name="Team A", value="\n".join(team_a), inline=True)
    embed_lobby1.add_field(name="Team B", value="\n".join(team_b), inline=True)
    await ctx.send(embed=embed_lobby1)


@lobby.command()
async def result(ctx, result):

    result = str(result)

    Team_A_channel = client.get_channel(870969338901954606)
    Team_B_channel = client.get_channel(870969338901954607)

    Team_A_members = Team_A_channel.members
    Team_B_members = Team_B_channel.members

    Team_A_members_id = []
    for member in Team_A_members:
        Team_A_members_id.append(member.id)
maiden fable
clever wind
slate swan
#

does someone khnows how to do a command like +addrole and it adds the role mentioned

waxen granite
#

how to add in a dict? append doesnt work

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild")...
flat solstice
#

so i have this mass ban command but I'm getting this errorpy NameError: name 'ban' is not defined ```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await ban(user, reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))

        await ctx.reply(f"{users} members were just banned.", delete_after = 5)```
unkempt canyonBOT
#

await ban(**kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.ban "discord.Guild.ban").
vagrant brook
#

Sorry, misread the error

spring flax
#

if member is your mmeber object, you do await member.ban(**kwargs)

vagrant brook
#

!d discord.Guild.ban

unkempt canyonBOT
#

await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
vagrant brook
#

I think this is what you're trying to do but ban is an attribute of guild so you need to call guild.ban

spring flax
#

its both

flat solstice
steady flume
#

wdym not found ?

#

pls help

flat solstice
#

it is loading your eco cog in the main file?

steady flume
#

i dont have cogs

#

here main

flat solstice
slate swan
#

?av @shy basin

#

!av @shy basin

spring flax
flat solstice
# spring flax you can do `await user.ban(reason = reason, delete_message_days = days)`

okay the command I'm using is ,massban 791394319075377243 757750333144563724 1 Testing and it's giving me py TypeError: ban() takes 1 positional argument but 2 were givenfor ```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await user.ban(user, reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))

        await ctx.reply(f"{users} members were just banned.", delete_after = 5)```do i need to `user = user` in the ban await
spring flax
#

its discord.Member.ban in this case

slate swan
#

hey guys i have this thingy that appears when i do the +help my command is not +help actually i didnt do this command and when i do it it shows me this what is it and how can i remove it ?

high flame
#

help_command=None in commands.Bot()

spring flax
slate swan
#

thx ^^

flat solstice
# spring flax remove user as the kwarg for the ban

think i'm just being dumb but i'm not following as I'm still getting the error```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await user.ban(user, reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.datetime.utcnow()))

        await ctx.reply(f"{users} members were just banned.", delete_after = 5)```so your saying I should make it `await discord.Member.ban(user, reason = reason, delete_message_days = days`. also is there a way I could pretty up the arg declarations for days and reason
spring flax
flat solstice
#

well I tried that and still got the error

spring flax
#

code?

flat solstice
#

testing it again removing user from the kwargs

slate swan
#

do buttons not work in dms?

#

does anyone nows how to do a +snipe command

flat solstice
# spring flax code?

okay well I think it's working. I got it to ban one of the two acc's I inputted. It told me it banned 0 ppl in the plain msg reply and it didn't send the embed at all```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
users = 0
for user in targets:
users += 1
await user.ban(reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.utcnow()))

        await ctx.reply(f"{users} members were just banned.", delete_after = 5)```
spring flax
#

not the issue but just saying

#

users += 1 to get the list of members that the user mentioned you can also use len() on that argument
len(targets)

flat solstice
#

oh yeah

spring flax
#

and you want it to reply to each member the user mentioned?

#

if he gave 5 members it would reply 5 times

slate swan
#

yeah and does everyone khnow how like change the name of the bot with a command like +set name

#

For mass ban I wouldn't really suggest using anything after the commands.Greedy[] pepeThinking

slate swan
#

uhm wait forgot what it is

flat solstice
slate swan
unkempt canyonBOT
#

await edit(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
spring flax
#

use that but instead of member, use ctx.me to edit the bot

flat solstice
# spring flax no errors for this?

Command: ,massban 791394319075377243 757750333144563724 1 Testing
Bot response: 0 members were just banned with reason 757750333144563724.
Code: ```py
@commands.command(description = "Lets moderators mass ban members.", alaises = ["multiban", "mass-ban", "multi-ban"], usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : int, reason : str):
with ctx.channel.typing():
days = days or 0
reason = reason or "Unspecified"
for user in targets:
await user.ban(reason = reason, delete_message_days = days)
await ctx.reply(embed = discord.Embed(title = "Member banned", description = f"{ctx.author} banned {user} for {reason}.",colour = ctx.author.color, timestamp = datetime.utcnow()), delete_after = 5)

        await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")```and it gave no errors. I tried making it ```py
async def massban(self, ctx, targets: commands.Greedy[discord.Member], days : Optional[int] = 0, reason : str):```but it gave me a syntax error (yes i'm importing optional and it works elsewhere i the cog
slate swan
spring flax
#

try mentioning the user

slate swan
#

days:int

flat solstice
spring flax
#

if it raises bad argument how would it give the message of how many users were banned?

stiff nexus
#
await ctx.send(f"{'{emoji.done} Meme is running' if self.meme.is_running() is True else '{emoji.error} Meme is not running'}")
```why its sending `{emoji.done}` instead of emojis
slate swan
# flat solstice okay mentions worked

If it's commands.Greedy set as discord.Member mentioning as many users as you want will always work but it's not really efficient to mention all the users let's say in the case of a raid Sadge

#

And it'll just take long

slate swan
#

just if x should work

stiff nexus
#

i edited it

slate swan
#

it's still kind of what it was before

flat solstice
slate swan
# flat solstice should I make it wait for a second or third msg. one which gives the reason and/...
@bot.command()
async def ban(ctx, members: commands.Greedy[discord.Member], delete_days: typing.Optional[int] = 0, *, reason: str):
    
    success = 0
    for member in members:
      await member.ban(delete_message_days=delete_days, reason=reason)
      success += 1

    await ctx.send(f"Banned the {success} members")

#error handler
``` I'm just thinking this may work a little better maybe tbh? Consider trying it and comparing to what you have ( edit as you want )
spring flax
#

bare try and except with pass Sadge

slate swan
#

edit as you want

flat solstice
slate swan
#

Theres anyone that can help me with a addrole command pls i'm trying it dont want to work

spring flax
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate swan
compact glen
#

don't ban me for this, but someone may need it

spring flax
slate swan
#

Bruh

#

Hmm..

stiff nexus
#

in title can i use custom emojis?

reef shell
#

yes

#

if you're talking about embeds, then yes

slate swan
#

I'm dumb

reef shell
slate swan
#

can anyone help me please? idk y but my bot calls the api 2 times at one command, whats wrong?

reef shell
#

check if your bot is running on multiple scripts or not

slate swan
#

thats all

#

what he meant was if ur bot is running multiple times

#

if not then show code

#

i dont think this is possible in my hosting, ill restart and check tho

#

should i send all of my code?

#

i restarted it and it happend again

pale turtle
#

Regenerate your token

slate swan
#

ok, ill try

valid niche
#

you're using a deprecated function, these functions are mainly userbot only functions

#

which indicates that you're using a userbot, which is highly against TOS and not allowed here

#

!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.

flat solstice
#

Is there a wait for message function or corotine? I want to add in a criteria to a command that my bot waits for a reaction from the user and then if a reaction is clicked then the bot waits for the user to type a msg and then I can make use of the msg

dawn wasp
#

Hey guys I'm trying to build a bot that pays music from a youtube url
I'm looking now into making playlist feature
did anyone already v done this ?

slate swan
#

god

#

i meant

#

ugh

#

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

finally

flat solstice
slate swan
#

yw

kindred epoch
pale turtle
#

||!ytdl||

slate swan
#

is discord really forcing everyone to move to slash commands if so im done being a developer and i know alot alot of people who agree

flat solstice
slate swan
#

otherwise you either have a good reason for discord to give you the intent (saying that u want it bc old commands were better won't work), either ur forced to use slash

#

My bot is growing and growing and im kinda scared about it should i start moving my commands to slash

#

yes

dawn wasp
slate swan
#

unless u plan to never verify it and cap your bot's total guilds to 100

#

Yes thats how groovy got shut down

kindred epoch
slate swan
#

pretty sure it's also against yt's tos

slate swan
kindred epoch
flat solstice
#

is there a way to set a string input as optional and to give it a default value? is it just string : typing.Optional[str] = "Deafault String or would I need to do something else

slate swan
#

string: str = "default string"

#

no need for typing.Optional

kindred epoch
#

ye

flat solstice
#

okay thanks

kindred epoch
#

if you add = "" it automatically converts to optional

slate swan
#

or just = None

kindred epoch
#

ye

flat solstice
#

well I've done this but it's not highlighting the str as green in the syntax but wrapping it in [] does

slate swan
#

yall know that d.py is no longer geting updates right

slate swan
slate swan
#

I moved everything to pycord

#

disnake >

#

disnake?

#

yes

pale turtle
#

!pypi disnake

unkempt canyonBOT
slate swan
#

disnake is another very good fork of dpy which is maintained by the creator of dislash

pale turtle
#

Oh man I hated dislash

slate swan
#

in my opinion better than pycord

slate swan
#

I see yea i moved to pycord because its d.py but forked and maintained

#

same with disnake

#

it has the exact same dpy 2.0 syntax with slash

pale turtle
#

The problem is it is import disnake and not import discord seems weird ngl

kindred epoch
slate swan
#

Pycord is more popular thats how i found it

kindred epoch
slate swan
#

¯_(ツ)_/¯

slate swan
pale turtle
#

Is there anything new cool in disnake that pycord doesn't have?

kindred epoch
slate swan
#

dislash is still maintained probably bc there's some ppl still using it

kindred epoch
slate swan
slate swan
pale turtle
slate swan
#

Anyways im to hooked to d.py so i use pycord almost if not nothing has changed

kindred epoch
slate swan
#

pycord does

pale turtle
kindred epoch
#

hm

#

ok

slate swan
#

disnake has that too

#

PyCord is most popular with over 300 stars and a lot of devs

#

i still hope for disnake to be at the top 😫

#

kinda like the name more too tbh

kindred epoch
#

cuz a yt'r owns it

slate swan
#

Yes but atleast i know that they wont just drop the project for no reason like danny did

#

pycord didn't even bother to change the pypi description

#

¯_(ツ)_/¯

kindred epoch
slate swan
#

only in the repo it's changed

slate swan
#

Im looking to use the most popular wrapper because that will be the one to get the fastest support with in this server

slate swan
#

Just like d.py this server pretty much dident know anything but d.py

#

other people dident even have a clue there was other wrappers

#

And now no one really know's which wrapper to use

Im waiting to see what carl-bot uses betting PyCord / Hi

#

idk if i'm just dumb but tf is with these docs on @bot.slash_command for pycord

#

what even are the kwargs

#

theres many

#

and where do i see them

#

just like if you were making a d.py command

#

but it doesn't work with commands.slash_command?

#

meaning that they won't work in cogs

#

🤦‍♂️

slate swan
#

PyCord does not support cogs atm

hasty iron
#

they’re all pretty much bad

slate swan
#

ikr

slate swan
slate swan
hasty iron
#

and will be

slate swan
#

^ or disnake

#

D.py will be gone in a month

Once discord pushes major api changes d.py is gone

hasty iron
#

a month?

#

what?

slate swan
#

Danny stoped maintaining it

#

there's still some new stuff that discord wants to add and since dpy stopped development it won't have those things

hasty iron
#

its still usable

slate swan
#

Im not making a bot growing it than a week later having to recode the whole bot using a new wrapper

#

not fun

hasty iron
#

that’s when you come in and update the wrapper yourself

slate swan
hasty iron
#

learning is always an option

slate swan
#

Not fun either

Thats why PyCord And Disnake are here

hasty iron
#

yeah nothing is fun

slate swan
#

^

#

hi

#

can anyone help me

#

?

hasty iron
#

ask, do not ask to ask

slate swan
#

ok

#

anyways i will be using pycord

#

look

#

because less than a week tell pycord gets cogs

slate swan
#

yes

#

i host bot and work

#

but if host replit and glitch or another hosting

#

have proplem

hasty iron
#

then dont use them

slate swan
#

Becuase folder named Accounts is missing

#

wait

#

Same with fortnite.txt

#

Jesus its in the error

#

is not fortnite

#

is all files

#

in folder

#

accounts

#

bangs head I give up

night crater
#

lets just take a chill out quickly

hasty iron
#

try relative path

#

.\path\to\file

night crater
#

this is a linux runtime

#

you sou want to use forward slashes

#

secondly

#

this bot looks very sketchy in terms of what it seems to do pithink

slate swan
#

yes

hasty iron
#

you even agree to it?

#

ok dud

slate swan
#

how to do

#

?

night crater
#

what?

slate swan
#

working

#

in host

night crater
#

well firstly

#

what is this bot for

night crater
#

Unless your bot absolutely needs the message intent you wont be getting the intent

slate swan
#

?

#

and

#

how can i fix it?

night crater
#

that wasnt aimed at you @slate swan

#

what is this bot for @slate swan

slate swan
#

acc gen

#

@night crater

night crater
#

okay, so, no

#

we're not going to help with that

#

because that breaks all sorts of Terms of service

#

both of Discord's and most likely the service you're creating account for

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
#

generate numbers

night crater
#

that doesnt matter

slate swan
#

and

#

is not acc gen

hasty iron
#

???

slate swan
#

is number

hasty iron
#

but you just said it is

pliant gulch
slate swan
#

is with commands

night crater
#

you just said it was

slate swan
#

wait i send code

night crater
#

secondly, just because it's random numbers

#

doesnt make it not tos breaking

#

Discord will ban you if you generate nitro links via random numbers or not

#

and this policy goes for any account generation

#

so no, we're not going to help with that.

slate swan
#

bruh

full lily
#

the funny thing is, that generating random account keys never ever works

flat solstice
#

Can someone help me understand how I should be doing my wait_for's? I have this command massban2 which takes a greedy input of discord members that need to get banned. I want to make the bot then ask me to add a reaction for if I want to add a ban reason. If I click ✅ then I want it to wait for a msg and save that msg to a variable. If I were to react with a ❎ tho then I want the bot to use a default reason. How close am I to getting this working and where might I be going wrong? ```py
@commands.command(description = "Lets moderators mass ban members.", usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban2(self, ctx, targets: commands.Greedy[discord.Member]):
with ctx.channel.typing():
confirmation = await ctx.reply(f"You are about to ban {len(targets)} members. Do you want to add a reason for this ban? If yes react with ✅ and if no react with ❎")
await confirmation.add_reaction("✅")
await confirmation.add_reaction("❎")

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == "❎" or "✅"

        try:
            reaction, user = await self.bot.wait_for('reaction_add', timeout = 60.0, check = check)
            reason = self.bot.wait_for()
        except asyncio.TimeoutError:
            confirmation.edit("The time to add a reaction timed out so the defualt reason of `Unspecified` will be used")
            reason = "Unspecified"
        else:
            reason = await client.wait_for('message')

        for user in targets:
            await user.ban(reason = reason, delete_message_days = 0

        await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")```
full lily
#

return user == message.author and str(reaction.emoji) == "❎" or "✅"
You have a problem with or here

#

you must have a full condition on both sides of the logical operator

slate swan
#

Also ```py
reason = self.bot.wait_for()

full lily
#

... str(reaction.emoji) == ":negative_squared_cross_mark:" or str(reaction.emoji) == ":white_check_mark:"

slate swan
#

Umm No.. rooThink

full lily
#

O.o

slate swan
#

It's just discord markdown to write emojis like that, comparing unicodes will work fine

flat solstice
#

would it be better to do a if statement than this function for the check?

full lily
#

oh it did that by itself

#

no, leave the check

slate swan
#

Make it a set and check if the emoji is in or not ```py
str(reaction.emoji) in {"❎", "✅"}

#

!e ```py
x = 1
print(bool(x == 2 or 3))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

True
slate swan
#

Should not be true, but it is ^

flat solstice
#

okay how's this looking?```py
@commands.command(description = "Lets moderators mass ban members.", usage = "massban [delete members message days] [reason] [members]")
@commands.bot_has_permissions(ban_members = True)
@commands.has_permissions(ban_members = True)
async def massban2(self, ctx, targets: commands.Greedy[discord.Member], delete_days: Optional[int] = 0):
with ctx.channel.typing():
#reason = reason or "Unspecified"
confirmation = await ctx.reply(f"You are about to ban {len(targets)} members. Do you want to add a reason for this ban? If yes react with ✅ and if no react with ❎")
await confirmation.add_reaction("✅")
await confirmation.add_reaction("❎")

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) in {"❎", "✅"}

        try:
            reaction, user = await self.bot.wait_for('reaction_add', timeout = 60.0, check = check)
            reason = await self.bot.wait_for('message')
        except asyncio.TimeoutError:
            confirmation.edit("The time to add a reaction timed out so the defualt reason of `Unspecified` will be used")
            reason = "Unspecified"

        for user in targets:
            await user.ban(reason = reason, delete_message_days = delete_days)
        await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")```Is this actually saying that if the reaction is ✅ then wait for the user msg but if it's ❎ then set a default value? or do I still need to do that
kindred epoch
#

you aren't checking which reaction they reacted to

#

so use if statements to check it

slate swan
#

Try it and see
... reason = await self.bot.wait_for('message') reason will be a Message object not a string, await ctx.reply(f"{len(targets)} members were just banned with reason {reason}.")

#

Does anyone khnow a code that massiverole evryone

kindred epoch
#

so do reason.content instead of reason

kindred epoch
#

give a specific role to everyone in the server?

slate swan
#

Like i'm tired of trying i want to make a command that gives a role a specific role to everyone

#

"gives a role a specific role to everyone"..?

kindred epoch
#

show what you have

kindred epoch
slate swan
#

Like

flat solstice
slate swan
#

It gives Everyone the role mentioned by the user 7529_KEKW

#

wait_for accepts events, like on_message, on_reaction_add and more, but just without on_

kindred epoch
slate swan
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate swan
#

I'm new at python bot coding

slate swan
kindred epoch
#

remove the bots and owners from it

slate swan
#

loop over all the members in the guild
rooMonkaS

kindred epoch
slate swan
#

ratelimit headers coming

kindred epoch
#

oh yea

#

so its probably a bad idea

slate swan
kindred epoch
#

thats why give the role to the member when they join the guild

slate swan
#

Yeah depends tbh, you can sleep the command every few seconds and use max_concurrency to prevent rate limits

#

But still not a good idea with a few thousand members

#

Another question can we like by a chance change the prefix of a bot with a command and without a database

#

without a database.. maybe

#

Because i was searching didnt find how to do it

#

All the tutorials persons said you need a database

#

you need some kind of storage to save the prefixes, and database is the only option. don't think about json

#

We can do a database in our pc or i need to buy a vps or anything else

#

If you can keep your pc turn on 24/7, sure

flat solstice
broken turtle
#
@bot.command()
@commands.has_permissions(manage_roles = True)
async def mute(ctx, user : discord.Member,*,reason= "No reason provided idot"):
    roleobject = discord.utils.get(ctx.message.guild.roles, id=870577969477857289)
    await user.add_roles(roleobject)
    await user.send("You have been muted in **Aurora  | Social • Icons • Anime** because:"+reason)
    await ctx.send(f":white_check_mark: {user} was muted")

i can nopt for the life of me figure out how to code a timed mute. but this is what i have so far

lone lichen
#

That way it works even if bot goes offline for a but

#

Bit

#

The problem w it is that it wont unmute on exact unmute date, it will have a bit of delay

flat solstice
#

also would could just use py await user.send("You have been muted in **{ctx.guild}** because:"+reason)orpy await user.send(f"You have been muted in **{ctx.guild}** because: {reason}")

lone lichen
broken turtle
#

thats what im thinking

wicked atlas
lone lichen
#

Or just asyncio.sleep but tgat would notvwork with longer periods of time

#

Best option is w db

#

Or json

wicked atlas
lone lichen
last moss
#

Why am I getting this error?

lone lichen
last moss
#
                embed = discord.Embed(title="You leveled up!", description=f"You are now level **{level}**", colour=0x00FF00)
                embed.set_thumbnail(url=helper.avatar_url)
                file=File(buffer,"rank.png")
                embed.set_image(url="attachment://rank.png")
                await helper.dm_channel.send(embed=embed,file=file)
lone lichen
#

Whats helper

last moss
#

a member object

lone lichen
#

Remove .dm_channel

#

Just member.send

#

It will dm them

last moss
#

member has no attribute send

#

oh

flat solstice
#

Can anyone see where i'm going wrong?py ERROR:cogs.error_handler:TypeError: edit() takes 1 positional argument but 2 were given (In massban2) Traceback: File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/moderation.py", line 363, in massban2 confirmation.edit(f"You are about to ban {len(targets)} members. Do you want to select how mnay days of the members messages get deleted? If **yes** react with ✅ and if **no** react with ❎")my code: https://sourceb.in/lqMvejLjMY

last moss
#

nm it does

lone lichen
last moss
#

it does

lone lichen
lone lichen
last moss
#

same thing happens

lone lichen
wicked atlas
lone lichen
#

I’ m on mobile, It’ s hard to see there

last moss
#
 File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\model.py", line 209, in invoke
    return await self.func(self.cog, *args, **kwargs)
  File "c:\Users\pc\Desktop\Projects\OCR-School\cogs\help.py", line 33, in exp
    await self.addExp(member, amount, ctx.guild, False)
  File "c:\Users\pc\Desktop\Projects\OCR-School\cogs\help.py", line 361, in addExp
    await helper.send(embed=embed,file=file)
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\dpy_overrides.py", line 323, in send_override
    return await send(channel, *args, **kwargs)
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\dpy_overrides.py", line 264, in send
    data = await state.http.send_files(
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 185, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 343, in request
    return _RequestContextManager(self._request(method, url, **kwargs))
TypeError: _request() got an unexpected keyword argument 'form'
flat solstice
lone lichen
flat solstice
wicked atlas
lone lichen
last moss
#

323?

#

why

flat solstice
#

Well my codes too long to send here so you can find it here: https://sourceb.in/2mfsV5IOdS. I'm having an issue where the bot is listening to my input for the reason but is not prompting me to input the num of days i'd like to delete and I'm not sure why

lyric moat
#

why is it doing this?

#

code

@client.command()
async def poll(ctx, *, question=None):
    if question == None:
        await ctx.send("Please write a poll!")
 
    icon_url = ctx.author.avatar_url 
 
    pollEmbed = discord.Embed(title = "New Poll!", description = f"{question}")
 
    pollEmbed.set_footer(text = f"Poll given by {ctx.author}", icon_url = ctx.author.avatar_url)
 
    pollEmbed.timestamp = ctx.message.created_at 
 
    await ctx.message.delete()
 
    poll_msg = await ctx.send(embed = pollEmbed)
 
    await poll_msg.add_reaction("⬆️")
    await poll_msg.add_reaction("⬇️")```
glacial echo
#

how dynamic is those fancy looking embeds with built in buttons? would it be possible to use them to make games with a join system for each round?

slate swan
#

Hello how do make the bot say a message instead of this error

I've tried this python elif isinstance (voiceChannel is None): await ctx.send("You not in vc kid") return and many others but they didn't work

patent lark
slate swan
patent lark
#

👍

slate swan
#

@patent lark can u help

#

@patent lark

#

nvm i guess ill just make a help channel

hybrid fjord
#

can someone link me the doc for the channel argument thing
e.g. async def test(ctx, channel:discord.Channel):

lofty heron
#

hi i've implemented a cooldown for my bot but i need it to send a message if CommandOnCooldown is triggered

#
async def on_command_error(ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
          embed = discord.Embed(
              title="error",
              description="run again in {round(error.retry_after, 1)} seconds",
              color=0xE02B2B
          )
          await ctx.send(embed=embed)
#

is this good?

graceful gulch
#

does anyone have any idea as to why bot.user returns None?

lone lichen
lofty heron
#

returns this

#

instead of sending the embed

#

hold on lemme add the commas

lone lichen
#

Which line of code makes it return this

lofty heron
lone lichen
lofty heron
#

um no

lone lichen
#

Then what prints that out in console

lofty heron
#

idk

lone lichen
#

Run the debugger

lofty heron
#

ok

lone lichen
#

Set a breakpoint in the command that causes this error

graceful gulch
lofty heron
boreal osprey
lone lichen
lone lichen
#

In which the command is

lofty heron
#

hmm

boreal osprey
#

i don't got a cog

lone lichen
errant snow
lofty heron
#

lol

boreal osprey
# lone lichen Show command
@client.event
    async def on_message_delete(message):
        client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)

    @client.command()
    async def snipe(ctx):
        try:

            contents, author, channel_name, time = client.sniped_messages[ctx.guild.id]
        except:
            await ctx.channel.send("No message was deleted!")
            return
         
        embed = discord.Embed(description=contents, color = discord.Colour.purple(), timestamp=time)
        embed.set_author(name=f'{author.name}', icon_url=author.avatar_url)
        embed.set_footer(text="caught in 4k")

        await ctx.channel.send(embed=embed) 
#
client.sniped_messages = {}
lone lichen
boreal osprey
lone lichen
#

Send ss of code

#

Not codeblock

#

Just those 2 functions

boreal osprey
#

this is at the top

lone lichen
#

Ok but I want snipe function

#

And on message delete

#

In one ss

boreal osprey
#

and this is the code

boreal osprey
#

what i mean by my function at the top

lone lichen
boreal osprey
#

doing the command you mean?

lone lichen
boreal osprey
#

k lemme get to my test server

lone lichen
#

It may be that event fucked a little w ur commands

slate swan
#

Does anyone khnow how to blacklist a member from the multiple servers that the bots are in

boreal osprey
#

k i still get the same error

slate swan
slate swan
#

delete the
client = discord.Client()
first

boreal osprey
lone lichen
#

Ohhhh

#

Mf u need bot = commands.Bot()

#

Not discord.cliient

slate swan
slate swan
#

without the mf

boreal osprey
#

ye i got bot = commands.Bot()

slate swan
#

no you don't

lone lichen
slate swan
#

lul

boreal osprey
#

i have it as client

#

client = commands.Bot()

lone lichen
#

Remove client = discord.Client bs, u dont need it

slate swan
#

bot = commands.Bot(command_prefix="your_prefix", help_command=None)

patent lark
#

use bot

slate swan
lone lichen
#

Bot = cmds.bot

#

Bame it bot

#

Not client

patent lark
#

its not wrong essentially, but using the bot as the variable is better practice since discord.Client() is a thing.

boreal osprey
#

amjsdbajkefbnaselfbaskfgaseg

lone lichen
#

Lmfao

boreal osprey
#

great now i gotta replace everything from client into bot

#

lmfao

slate swan
#

there's supposed to be a replace everything thingy in your IDE...

lone lichen
#

Naming is one of most important things in coding, make sure u get it right at the start or u gonna have to fuck w it later

boreal osprey
#

ive always had it as client

#

not bot

slate swan
#

youtube tutorials

lone lichen
#

Fr

#

Dude in yt tutorial I watched had client too

boreal osprey
#

alot of this server uses client

lone lichen
#

But bot is correct

slate swan
#

the thing is, client is not made for command usages

boreal osprey
#

hmm

#

so i replace with bot

lone lichen
#

Yea

boreal osprey
#

how to i replace everything that was client into bot

lone lichen
#

What ide u using?

slate swan
#

VS Code on top

boreal osprey
#

vsc

lone lichen
#

Idk shortcut for that one

slate swan
#

select a client in your code, click on replace every o... something and type bot

lone lichen
#

It’ s shift + f6 in pycharm

slate swan
#

lemme check

vapid lotus
slate swan
#

you select something

vapid lotus
#

he locked repo

#

so sad

#

so pain

slate swan
#

right click
click on change all occurrences

#

and type in bot

lone lichen
vapid lotus
#

yeah but he not updating

boreal osprey
#

ok yay

lone lichen
#

Yea, if something breaks u gotta update urself

boreal osprey
#

it changed it

lone lichen
#

Now run

#

And show error

graceful gulch
#
    asyncio.run(bot.wait_until_ready())
  File "D:\Python 3.9.1\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "D:\Python 3.9.1\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "D:\Python 3.9.1\lib\site-packages\discord\client.py", line 890, in wait_until_ready
    await self._ready.wait()
  File "D:\Python 3.9.1\lib\asyncio\locks.py", line 226, in wait
    await fut
RuntimeError: Task <Task pending name='Task-1' coro=<Client.wait_until_ready() running at D:\Python 3.9.1\lib\site-packages\discord\client.py:890> cb=[_run_until_complete_cb() at D:\Python 3.9.1\lib\asyncio\base_events.py:184]> got Future <Future pending> attached to a different loop

now i get this error when using bot.wait_until_ready() (I am not too well versed in asycnio)

boreal osprey
slate swan
#

didn't check it out, but this was the first thing that I found

#

and it had a reply with a tick

#

complicated solution, good luck mate

boreal osprey
slate swan
#

show your code

#

without the token

boreal osprey
#

the snipe command code?

slate swan
#

yes

boreal osprey
#

i have a function at the top

slate swan
#

interesting

boreal osprey
#

do you need my function?

slate swan
#

show me the top of your code rn

#

that you have now

boreal osprey
slate swan
#

two on_ready events

boreal osprey
#

ye

slate swan
#

just put the content of your second one to the first one

#

and delete the second one

#

you can't have two of the same events

graceful gulch
slate swan
#

lol

boreal osprey
slate swan
#

I don't know if that could have caused the problem

#

try running the code

boreal osprey
#

this is saying that the command isn't found

#

but ill try

#

nice

#

it still gives me a error

#

akefbnjkfbadskgbaslkgsarg

trim fulcrum
#

Show new code

hasty iron
#

i saw your code before and the snipe command was inside the on_message_delete event

#

that’s the issue

slate swan
#

now it's not

hasty iron
#

then did it work?

slate swan
#

but ig it still doesn't work

hasty iron
#

did you save your code

boreal osprey
#

kjewbfkuweblewgbase

#

yes

slate swan
#

stop spamming lmao

hasty iron
#

can you show your full code

#

!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.