#discord-bots

1 messages · Page 761 of 1

jovial osprey
#

how can i make bot create text channel with embed in it ?

quaint scaffold
unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
quaint scaffold
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
quaint scaffold
#

The documentation offers all the necessary resources, if you are stuck on the actual execution or construction, ask for help.

quick gust
#

yes

quaint scaffold
#

Fyi you can remove the string slice and replace it with the .display_name / .name attribute of a discord.Member object

jovial osprey
quaint scaffold
#

You just need to supply the kwargs you want, you can do this in one line

#

e.g. name = 'general-chat'

#

discord.py was not intended to be used by beginners, if you find the concept of kwargs or async code confusing, please learn that first

wary ice
#

how can i put mobile phone status on the boot

quaint scaffold
#

It's not advised to do so, it's a bug in the Discord API and will be patched. Bots shouldn't have mobile statuses

wary ice
#

Ok

slim whale
#
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
  server=ctx.guild
  ban_list = await bot.get_bans(server)
  await ctx.send('Desbaneando a todos los miembros.')
  for member in ban_list:
    await ctx.guild.unban(member)``` I'm trying to unban 1700 people. This is the traceback: ```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 40, in unban
    ban_list = await bot.get_bans(server)
AttributeError: 'Bot' object has no attribute 'get_bans'

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/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: AttributeError: 'Bot' object has no attribute 'get_bans'```
slim whale
#

how i can do it?

quaint scaffold
#

!d discord.Guild.bans

unkempt canyonBOT
#

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

Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
kindred epoch
#

You don't need to iterate through the list/ you don't even need to get all the bans from the guild.

#

!d disnake.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.Snowflake "disnake.abc.Snowflake") abc.

You must have the [`ban_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.ban_members "disnake.Permissions.ban_members") permission to do this.
kindred epoch
#

Just use that

slim whale
#

so like server.bans()

slim whale
#

okay

#

i'm going to check it

#

thank u guys

kindred epoch
#

If the member is not banned it will raise an error

quaint scaffold
#

You will need to iterate through the entire guilds' bans to unban more than one person

#

Fyi sending 1700 consecutive API requests to Discord to unban that many people will have your bot ratelimited

#

And IP blocked temporarily

jade sinew
#

Helloo, so i think this is more of a replit problem than actual bug int he code. so i put my discord bot code into replit and then ran it, and instead of running it gave me this error: ```
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because repl-python3-challengebot depends on both aiohttp (^3.8.1) and discord (^1.7.3), version solving failed.

at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes
exit status 1

Replit: Package operation failed.``` so basically aiohttp and that python version aren't really cooperating? Can someone pls tell me how to fix this? I'm very new to repl, so this may seem easy to some of you. pls ping when you respond

#

ive tried doing a different repl, but that seems to have no effect whatsoever

quaint scaffold
#

Long story short, don't use replit @jade sinew.

You should not use Repl.it to host your bot.

While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

cloud dawn
#

avatar.url

jade sinew
quaint scaffold
#

If you have any money, purchase a VPS, they're around $4 per month

kindred epoch
#

No free hosts are as good as paid ones. And that they aren't even for discord bots to be hosted on.

jade sinew
#

i have $0 money and no credit card even if i did

kindred epoch
quaint scaffold
#

GitHub student packs offer free DigitalOcean credits.

jade sinew
#

but im not a github student

quaint scaffold
#

Are you a student?

jade sinew
#

yes

cloud dawn
#

Netcup has hosting starting at 2.80 eu

quaint scaffold
#

Apply for it

#

If you provide a school email, you'll get it really quickly

#

Oh, and AWS gives a free year I believe

jade sinew
#

i tried using heroku, but once i tried hosting multiple bots i lost my free dyno hours

kindred epoch
#

Bruh

jade sinew
#

hmm these suggestions all sound great! thanks!

untold token
quaint scaffold
#

If you're a student, take advantage of the GitHub student pack, it's wild

jade sinew
#

ill try them all out

untold token
#

your aiohttp version is causing issues

#

use aiohttp@3.7.4.post0

cloud dawn
#

GitHub pack also gives azure 100 bucks

untold token
#

That should fix the issue

jade sinew
quaint scaffold
#

Just don't use replit, it's the wrong way to start out programming

jade sinew
untold token
jade sinew
#

ohh

quaint scaffold
#

-_-

untold token
#

poetry add aiohttp@3.7.4.post0

jade sinew
#

lol ty

untold token
# quaint scaffold -_-

Yeah you should not use replit I know but its actually not the issue with replit but poetry

cloud dawn
#

Well repl.it can be used but not for hosting debugging if on phone at most

jade sinew
#

ok

quaint scaffold
#

It's better suited for things like Flask and Django web apps. But at that point you may as well use a VPS

#

Better to learn web development that way imo

#

Nginx + gunicorn doesn't hurt anyone

cloud dawn
#

You don't

untold token
#

You can't "hide" slash commands

#

you can change the permissions the to grey them out

cloud dawn
#

Since slash commands are meant for users and not for devs to debug

cloud dawn
untold token
#

I mean yeah, you can't do much anything more than that

#

slash commands permissions v2 is still developed by discord

cloud dawn
#

I have a slash bot aswell that I'm coding rn

#

I combined both slash and prefix. Using the prefix for debugging, no help command no bot responses just for debugging.

kindred epoch
#

Well, technically you can make slash commands not visible in other guilds besides the ones you want

untold token
#

@jade sinew did it work?

cloud dawn
#

If you would ever make them global

untold token
#

That's an ephemeral message

jade sinew
untold token
#

Ah okay

#

With disnake it's pretty easy to make

#
@bot.slash_command(name="test")
async def (inter: disnake.ApplicationCommandInteraction):
    await inter.response.send_message("hello", ephemeral=True)
#

That's it

#

the ephemeral kwarg needs to set to True and you will be able to send ephemeral messages

#

Oh wait, you meant hidden slash commands this?

#

Oh I thought you were talking about hiding the slash command itself

#

Ah

rugged laurel
#

would this channel fit for asking how to make my chatbot into a discord chatbot?

modest plover
#

In the command, with the db.execute things, does it put me at this stage?

#

Fuck forgot the reply

#

^

honest vessel
rugged laurel
#

so i got this python chatbot thats completely unrelated to discord, is this where i should ask how to make it into a discord chatbot?

honest vessel
#

@rugged laurel start read about how to write a discordbot and u will understand how merge them both, https://docs.disnake.dev/

fervent shard
#

code: py @commands.command(aliases=["ub"]) @commands.has_permissions(ban_members=True) async def unban(self, ctx, member:discord.User, *, reason="none"): user = await self.bot.fetch_user(member.id) try: em1=discord.Embed(description=f"{member.mention}, you have been `unbanned` for **{reason}**", colour=0) await user.send(embed=em1) except: pass em2=discord.Embed(description=f"{member.mention} has been `unbanned` for **{reason}**", colour=discord.Colour.green()) await ctx.send(embed=em2) await ctx.guild.unban(user, reason=reason)error:

discord.ext.commands.errors.CommandNotFound: Command "unban" is not found```
tawdry perch
#

Did you load the Cog?

fervent shard
tawdry perch
#

You know what that is right?

tawdry perch
unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
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/master/ext/commands/cogs.html#ext-commands-cogs) page.

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

You didn't pass member to that command

cloud dawn
#

I don't recommend copying code

fervent shard
cloud dawn
fervent shard
fervent shard
honest shoal
fervent shard
honest shoal
honest vessel
#

i would't copy it but more take some references from it

#

it was more likely i rushed it...

#

parameter's name is bad and alot in that code is bad

cloud dawn
#

lmfao

honest vessel
#

but i had to type, cause u try tell others u rushed it 🙂

honest shoal
#

Imagine banning users instead of members

modest plover
rugged laurel
#
client.run(TOKEN)

with open('words.json') as f:
  dit = json.load(f)

@client.event
async def on_message(message, word):
    username = str(message.auther).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.auther == client.user:
        return

    if message.channel.name == 'testing':
        if word == 'add.pattern':
        key = input('Enter the word: ').lower()
        value = input('Enter A.I. response: ')
        
        dit[key] = value

        with open('words.json', 'w') as f:
            json.dump(dit, f)
        
        word = input('? ').lower()
    
    elif word in dit:
        print(dit[word])

        word = input('? ').lower()
    
    else:
        word = input('? ').lower()

    if word not in dit:
        key = input('I dont think i understand, please repeat the word.: ').lower()
        value = input('Enter A.I. response: ')

        dit[key] = value

        with open('words.json', 'w') as f:
            json.dump(dit, f)

        word = input('? ').lower()

can anyone help me fix the error im getting on line 31, 9

#

its something with "key" not working

#

i need to fix this so it works with the discord py library

slim ibex
#

what’s the error

cloud dawn
slim ibex
#

^

cloud dawn
#

First of all this code can never be reached.
Second of all this is very blocking.

slim whale
#
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
  server=ctx.guild
  ban_list = await server.bans()
  await ctx.send('Empezando a desbanear a todos los miembros.')
  for ban_entry in ban_list:
    member = ban_entry.user.id
    await server.unban(member)
  await ctx.send('He acabado de desbanear a todos los miembros.'
  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 45, in unban
    await server.unban(member)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 2052, in unban
    await self._state.http.unban(user.id, self.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'

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/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: AttributeError: 'int' object has no attribute 'id'```
#

why do i get this traceback?

slim ibex
#

it’s not server.unban

rugged laurel
slim ibex
#

context.guild.unban(member)

#

Oh wait

slim whale
slim ibex
#

You set server to ctx.guild

slim whale
#

ye

slim ibex
#

yeah

slim whale
#

idk why i get that xd

slim ibex
#

tbh I would put that stuff in the params but it doesn’t matter

slim whale
#

but why i get that traceback

#

i dont get it xd, dont know what its wrong

slim ibex
#

How do you invoke the command

slim whale
#

invoke? like -unban

#

im from spain so idk what that means xd

rugged laurel
#

PS C:\Users\esben\Desktop\Bob the Chatbot> & C:/Users/esben/AppData/Local/Programs/Python/Python36/python.exe "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py"
Traceback (most recent call last):
File "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py", line 8, in <module>
client = discord.client()
TypeError: 'module' object is not callable
PS C:\Users\esben\Desktop\Bob the Chatbot>

im getting this error, ima send script rl quick

slim ibex
#

how do you type it in discord

slim whale
#

-unban

slim ibex
#

that’s it? you don’t specify a user?

slim whale
#

no, its a unban all

unkempt canyonBOT
#

Hey @rugged laurel! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

slim whale
#

so i have the id of every member but the bot doesnt unban them

rugged laurel
#

oop

modest plover
#

That's no good lmao

slim whale
#

and i get that traceback

rugged laurel
#
from asyncio import events
import json
import discord
import random

TOKEN = ""

client = discord.client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

client.run(TOKEN)

with open('words.json') as f:
  dit = json.load(f)

@client.event
async def on_message(message, word):
    username = str(message.auther).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.auther == client.user:
        return

    if message.channel.name == 'testing':
        if user_message in dit:
            await message.channel.send(dit[word])
        

        word = user_message('? ').lower()
    
    else:
        word = user_message('? ').lower()

    if word not in dit:
        await message.channel.send(f'i dont think i understand')
#

so how do i fix error

#

PS C:\Users\esben\Desktop\Bob the Chatbot> & C:/Users/esben/AppData/Local/Programs/Python/Python36/python.exe "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py"
Traceback (most recent call last):
File "c:/Users/esben/Desktop/Bob the Chatbot/discord-bot.py", line 8, in <module>
client = discord.client()
TypeError: 'module' object is not callable
PS C:\Users\esben\Desktop\Bob the Chatbot>

slim ibex
#

remove .id from ban_entry.user.id

steel slate
#

Hello, I have a question i wrote this for out of the cog but i want it to work in a cog i have it this far but i get a name error py @commands.Cog.listener() async def on_ready(self): for guild in client.guilds: print(guild.name) print( f'{client.user} is connected to the following guild:\n' f'{guild.name}(id: {guild.id})\n' )

slim whale
#

okk

rugged laurel
slim whale
#

it works, thank u! @slim ibex

cloud dawn
quick gust
rugged laurel
#

thats all?

rugged laurel
#

i feel insanely stupid😂

quick gust
#

or whatever you have named your bot instance

quick gust
rugged laurel
#

wait

#

its not working

#

the dit isnt working it aint getting from words.json

#
client.run(TOKEN)

with open('words.json') as f:
  dit = json.load(f)

@client.event
async def on_message(message, word):
    username = str(message.auther).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.auther == client.user:
        return

    if message.channel.name == 'testing':
        if word == 'add.pattern':
        key = input('Enter the word: ').lower()
        value = input('Enter A.I. response: ')
        
        dit[key] = value

        with open('words.json', 'w') as f:
            json.dump(dit, f)
        
        word = input('? ').lower()
    
    elif word in dit:
        print(dit[word])

        word = input('? ').lower()
    
    else:
        word = input('? ').lower()

    if word not in dit:
        key = input('I dont think i understand, please repeat the word.: ').lower()
        value = input('Enter A.I. response: ')

        dit[key] = value

        with open('words.json', 'w') as f:
            json.dump(dit, f)

        word = input('? ').lower()

this is original python terminal code

rugged laurel
#

like it launched

#

but it doesnt repply to me

cloud dawn
#

@rugged laurel I'm sorry but it's fair to say you skipped the basics of Python, i recommend learning that first then get back to it.

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

rugged laurel
steel slate
cloud dawn
honest vessel
#

username = str(message.auther).split('#')[0]
if message.auther == client.user:
its author tho

#

@rugged laurel

rugged laurel
#

wdym

honest vessel
#

.auther not correctly spelled

rugged laurel
#

oh

quick gust
#

wherever you would normally use client just make it a thumb rule to add self before that. E.g

bot.py:

client.user
client.guilds```

cogs
```py
self.client.user
self.client.guilds```
rugged laurel
#

lol

steel slate
honest vessel
#

@cloud dawnhey its a hard word if non english speaking n maybe dyslexia 🙂

quick gust
#

No worries

cloud dawn
rugged laurel
honest vessel
rugged laurel
#

nope

#

still i dont get response

#

wait

#

nope

rugged laurel
#

its prob prefix problem

rugged laurel
wooden viper
#

can anyone tell me why my loop isnt working inside my cog?

class updates(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.index = 0

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

def setup(client):
    client.add_cog(updates(client))```
wooden viper
cloud dawn
#

self.printer.start()

wooden viper
#

thanks

rugged laurel
#

wait how do i make a bot that has a database of words and patterns, and then a command to create new ones?

#

and then the command should be like /ap:Hi:Hello

cloud dawn
rugged laurel
#

ik

cloud dawn
steel slate
#

how do i take the commands out of cog and put them in cog?

foggy merlin
#

When I first start my bot, all the @tasks.loop run. Is there a way to immedietely add the delay. So if I have tasks setup to run every 1 hour, it will run 1 hour after the bot has started

cloud dawn
steel slate
cloud dawn
#

@daring olive Sorry for the ping :3
Thought you might be interested.

maiden fable
#

Wait what's this?

daring olive
#

yup i saw

maiden fable
#

You DMed ModMail to ask a Discord API question???

daring olive
#

i was a part of the discussion lol

cloud dawn
maiden fable
#

Ah, joining random servers from bot.guilds?

daring olive
#

rereading that code yesterday, i also noticed the docstring in the function was misleading right?

#

the docstring seemed to indicate that it would create and post an invite link in the topmost channel of the server

cloud dawn
tidal hawk
#

How to make tasks.loop execute randomly between 1-3 hours?

tidal hawk
#

tasks.loop(hours=random.randint(1, 3))

#

that easy huh

cloud dawn
dense swallow
#

is SQLite good for bots? some say it's not good?

cloud dawn
#

Do use the aiosqlite lib though

dense swallow
#

what about medium

#

medium bots

cloud dawn
#

How many guilds?

dense swallow
#

like around 500?

cloud dawn
#

That is still considered small

dense swallow
#

what's the range of "small bots"?

cloud dawn
#

sqlite is for around 20/25k guilds

dense swallow
#

oh damn

honest vessel
dense swallow
honest vessel
dense swallow
#

yeah

honest vessel
#

@dense swallowwhen u got ur sql up consider do daily backups or so too

dense swallow
#

to not lose data?

honest vessel
#

yeah

#

if shit hits the fan

dense swallow
#

😂 k

honest vessel
#

or if u misstaken ly does something

dense swallow
#

hmm yeah

honest vessel
#

then u can also delete old backups that are too old

dense swallow
#

I was considering switching to mongo, but I really don't like the syntax and Postgres hosting costs a lot for good one

honest vessel
#

i nvr been intressted in mongo :S

dense swallow
#

same

honest vessel
#

its sqlite for local db, or prettymuch mysql for remote db

dense swallow
#

I really like pg, but what to do if I can't afford it

#

(hosting)

honest vessel
#

u can get cheap vps

dense swallow
#

I don't have any income

honest vessel
#

ah

#

so how u host ur bots?

#

freehosting?

dense swallow
#

yeah

#

not replit tho, used to use it but left it since it's so bad

honest vessel
#

but u dont even have $5 month?

dense swallow
#

how can a student earn?

honest vessel
#

oh in sweden students gets like 100+$ just being a student each month

#

prob more

dense swallow
#

:O

#

part time jobs?

honest vessel
#

no thats what all students gets

#

from gov cause they being students

dense swallow
#

what

#

that's crazy

#

how can the govt give every students $100+

honest vessel
#

137$ each month for free

dense swallow
#

as a scholarship or smth?

#

or simply

honest vessel
#

no just bein going to school

dense swallow
#

hmm

honest vessel
#

from when u 16yo till 20yo

#

i guess sweden has it pros 😛

steel slate
#

Hi i have my welcomer that was made out of cog but i am working on classing items so i was wondering how to convert to cog and want to make sure it is correct because i don't have a test function ```py
#Client Events

@commands.Cog.listener()
async def on_member_join(member):
    if member.guild.id == 804864012184977438 : return
    channels = member.guild.channels
    for channel in channels:
        if ('welcome' in channel.name) or ('joins' in channel.name): #or ('testing' in channel.name)
             embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!")
             embed.set_thumbnail(url=member.avatar_url)

        await channel.send(embed=embed)

@commands.Cog.listener()
async def on_member_remove(member):
    if member.guild.id == 804864012184977438 : return
    channels = member.guild.channels
    for channel in channels:
        if ('leave' in channel.name) or ('Goodbye' in channel.name): #or ('testing' in channel.name):
            embed=discord.Embed(title=f"Goodbye, {member.name}", description=f"Bye {member.name} come again soon")
            embed.set_thumbnail(url=member.avatar_url)
            
            await channel.send(embed=embed)```
compact pelican
#

Hello, is there a way to get the first channel in a category and move it into another one ?

#

I know how to move a channel to another category but i don't know how to get the first channel of a category.

honest vessel
#

dunno and too lazy just ate, but grab the category
u want -> category.channels[0] something that way

quick gust
quick gust
crystal cliff
#

How do i send a user a dm from d.py This is my code = @Bot.command()
async def DM(ctx):
user_id_list = [user_id]
for user_id_list in user_id_list:
user = await Bot.get_user_id(user_id)
await user.send('this is a test dm')

leaden chasm
#

anyone know to how to add gif emojis to py i tried the old method but it didn't work

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.

velvet tinsel
# maiden fable yea this is how u do it

I mean... you can do

@bot.command()
async def dm(ctx, member: discord.Member):
  await member.send(...)

but I think they wanted to DM everyone 🤷‍♂️

leaden chasm
# maiden fable wym

like for example if you wanted to add a gif emoji to your welcome command, how would i do that?

maiden fable
#

u need its ID and name

#

u get this with \:emoji-name:

#

and add this to yr code

velvet tinsel
leaden chasm
#

ah

#

so like this

#

nvm got it ty

#

so much

maiden fable
velvet tinsel
#

flexing your nitro

maiden fable
#

gonna end in a day or two

velvet tinsel
#

oh

maiden fable
#

wait its ending today :DDD

velvet tinsel
#

enjoy it while it lasts

ebon island
#

How difficult is it to create a website splash page like most high quality bots have? Is there a framework for building them?

maiden fable
#

yea

#

!pypi flask-discord

unkempt canyonBOT
maiden fable
#

there are extensions for those

#

!pypi discord-ext-ipc is also there

unkempt canyonBOT
ebon island
#

Cool, thank you 🙂 I'd assume there is additional work to be done, say creating a react frontend or something to make it look more attractive as I know flask apps don't by default look very appealing

maiden fable
#

For that, u can look into jinja2

velvet tinsel
# unkempt canyon

don't you just need a button and a redirect to the invite link? Or...

maiden fable
#

Or you can also look into svelte and Brython @ebon island

maiden fable
velvet tinsel
#

o

ebon island
#

No, I am looking for a dashboard framework for customizing settings and all via dashboard

#

I will look into them 🙂 What are the key differences in each?

maiden fable
#

Ah, well the most basic implementation for something like that would be: Suppose u have an option to change the logging channel, then u display the list of all the channels u got, after requesting them from the bot and show them on the website... When the user clicks one, u just edit the database

maiden fable
ebon island
#

Found a relevant YT video, appears by the code snippets seen in the video to be JS but it's definitely something to consider while I continue searching for a Python based implementation

maiden fable
#

Talking about svelte?

#

Its just an easier way to combine HTML and JS codes haha

Its a programming cum markup language in itself

#

And then there is sveltekit, a framework similiar to React implemented in Svelte to create backend and frontend, still in beta tho

#

So what u can do is, create a websocket connection with the bot, and just request for things through it... That is what discord-ext-ipc does

echo wasp
#

So i am using an ignoring fuction in my welcome and leave is there a way i can have a document like a .txt file with all the id's in it that it checks?

slate swan
#

use a db

#

.txt files arent fit to store data

#

if you did read a text file would it just be one long string?

#

i think so im not sure

distant tree
slate swan
#

your params

distant tree
slate swan
distant tree
#

i honestly don't see an issue

distant tree
#

it's in the pastebin

slate swan
slim ibex
#

You have to invoke it in the order of the params

slate swan
#

^

distant tree
slate swan
#

seems like you have something wrong

slim ibex
#

^

#

it says member “5s” not found

#

Obviously the ID is not being treated as the member

slate swan
#

yeah

distant tree
#

once again it's in the pastebin.

#

it's been broken like this for a few days

#

it's saved

slim ibex
#

any errors in terminal?

slate swan
#

it thinks temp is the member

distant tree
slate swan
#

your adding extra params
<prefix><ctx><another_argument><member_obj><duration>

distant tree
slate swan
#

ahhh ic

#

btw thats not following pep8 lol

#

maybe change the argument order

slim ibex
#

Does the regular mute work

steel slate
#
    async def Ping(self, ctx):
        await ctx.channel.send(f"**pong!** That took {int(self.bot.latency*1000)} ms!")```
#

worked fine out of cog

slim ibex
#

self.bot

steel slate
slate swan
slim ibex
#

^

#

Was about to say that

steel slate
#

ok

#
import os
import discord
import time
import datetime
import asyncio
from discord.ext import commands

class CMS(commands.Cog):

    def __init__(self,client):
        self.client = client

#Ping command
    @commands.command(name='Ping')
    async def Ping(self, ctx):
        await ctx.channel.send(f"**pong!** That took {int(self.bot.latency*1000)} ms!")
    


#Purge command
    @commands.command(name='Purge')
    @commands.has_permissions(manage_messages=True)
    async def Purge(self, ctx, limit: int):
        await ctx.message.delete()
        await asyncio.sleep(1)
        await ctx.channel.purge(limit=limit)
        purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
        purge_embed.set_footer(text=str(datetime.datetime.now()))
        await ctx.channel.send(embed=purge_embed)




#Help Command
    @commands.command(name='Help')
    async def Help(self, ctx):
        embed=discord.Embed(title='Help Page!', description=f"%Ping (To tell you if I am online or not) \n %Purge (To purge mass messages) \n %Invite (Opens the invite page to invite me!) \n %Help (To open this page to tell you what commands I have)", color=0x206694)
        await ctx.channel.send(embed=embed)



def setup(client):
     client.add_cog(CMS(client)) ```
#

Help command works trying purge work

slim ibex
#

self.client

slate swan
#

were the heck i cant find it lol

echo wasp
#

what you looking for

slate swan
#

like binds said lol

#

your bot isnt named bot in this case its client

echo wasp
#

ok

steel slate
#

fixed it

slate swan
#

noice

steel slate
#

now how do you add a false statement on a purge command as what i have above

slate swan
#

theres no such thing as a false statement

#

False is a bool

steel slate
honest vessel
#

@steel slateu should try read some about python 🙂

slate swan
honest vessel
#

or u gonna keep asking for simple things over n over

slate swan
#

i got it

steel slate
slate swan
#

chill out

slate swan
steel slate
slate swan
#

wdym by false statement?

steel slate
# slate swan what about it

you know like how carl bot says you don't have perms todo that but if you do have perms he does it like that

steel slate
slate swan
#
@commandname.error
async def example_error(self, ctx, error: commands.CommandError):
    if isinstance(error, commands.MissingPermissions):
          await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")

something like this

#

this just checks if the error is the given instance

slate swan
#

yw

steel slate
# slate swan yw

also how do i make it so if you don't put a number it just doesn't do anything?

#

it tells you to add a number

slate swan
#
if type(limit) == str:
    # do something
#

if you have a command error it will just handle it as a bad argument

#
@client.command()
async def testt(ctx):
    await ctx.send("hello", components = [
        [Button(label="hi", style="3", emoji= "🛴", custom_id="button1"), Button(label="hi2", style="4", emoji= "🛴", custom_id="button2")]
    ])
    interaction= await client.wait_for("button_click", check= lambda i: i.custom_id == "button1")
    await interaction.send(content = "test done")

Interaction failed?

steel slate
#

i ment like the person does %purge it won't do anything i want it to comback and say this is how you need to do it

slate swan
slate swan
#
if type(limit) == str:
    return await ctx.send("you must do the command as so....")
steel slate
#
   @commands.command(name='Purge')
    @commands.has_permissions(manage_messages=True)
    async def Purge(self, ctx, limit: int):
        await ctx.message.delete()
        await asyncio.sleep(1)
        await ctx.channel.purge(limit=limit)
        purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
        purge_embed.set_footer(text=str(datetime.datetime.now()))
        await ctx.channel.send(embed=purge_embed)
    @Purge.error
    async def Purge(self, ctx, error: commands.CommandError):
        if isinstance(error, commands.MissingPermissions):
          await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")
slate swan
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

must have no level of indentations

steel slate
#

should be under the await?

slate swan
steel slate
slate swan
#

lol

steel slate
#

that is how it is set

slate swan
#

thats how it inherits everything in the cog since its in it

steel slate
#
import os
import discord
import time
import datetime
import asyncio
from discord.ext import commands

class CMS(commands.Cog):

    def __init__(self,client):
        self.client = client

#Ping command
    @commands.command(name='Ping')
    async def Ping(self, ctx):
        await ctx.channel.send(f"**pong!** That took {int(self.client.latency*1000)} ms!")
    


#Purge command
    @commands.command(name='Purge')
    @commands.has_permissions(manage_messages=True)
    async def Purge(self, ctx, limit: int):
        await ctx.message.delete()
        await asyncio.sleep(1)
        await ctx.channel.purge(limit=limit)
        purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
        purge_embed.set_footer(text=str(datetime.datetime.now()))
        await ctx.channel.send(embed=purge_embed)
    @Purge.error
    async def Purge(self, ctx, error: commands.CommandError):
        if isinstance(error, commands.MissingPermissions):
          await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")



#Help Command
    @commands.command(name='Help')
    async def Help(self, ctx):
        embed=discord.Embed(title='Help Page!', description=f"%Ping (To tell you if I am online or not) \n %Purge (To purge mass messages) \n %Invite (Opens the invite page to invite me!) \n %Help (To open this page to tell you what commands I have)", color=0x206694)
        await ctx.channel.send(embed=embed)



def setup(client):
     client.add_cog(CMS(client)) ```
brittle flume
#

Can command_prefix be a list?

steel slate
slate swan
brittle flume
steel slate
#

it is just classes

slate swan
#

just basic subclassing lol

slate swan
steel slate
#

so does it sit like that or how should it si

#

t

slate swan
#

just like that

steel slate
#

ok i still have that error

slate swan
#

try naming the function something else

#

in the error handler

#

and i have to check if error handlers are different in cogs

steel slate
#

might be idk

#

what should i name the eror handler?

slate swan
#

anything lol

steel slate
#

ok at the @ part or just the def

slate swan
#

and do @cog_Purge.error

slate swan
steel slate
slate swan
#

yes should be like that

steel slate
#

ok testing

#

but that wasn't the error

slate swan
#

wdym

steel slate
#

i didn't do %purge 1 i just did %purge

#

that works for non perm people

slate swan
#

make it a positional arg

#

or make it an optional

steel slate
#

on permed people

slate swan
#
if not limit:
    ...

and add a default value of None

slate swan
steel slate
crystal cliff
steel slate
slate swan
#

on top

steel slate
#

like here?

slate swan
#

yes

#

but indent it

steel slate
#

ok

#

can i put in an await on it

slate swan
#

where

#

in the if statement no?

steel slate
slate swan
#

thats indentation

steel slate
slate swan
steel slate
#

do i need to indent it?

#

or how do i fix that

slate swan
#

wait nvm

#

you have to send the embed and return the function

#

in the if statement

#

thats all

steel slate
slate swan
#

and your if statement isnt indented well

#

^

steel slate
#

ok here

crystal cliff
slate swan
#

probably does

steel slate
slate swan
#

but use the timestamp kwarg

slate swan
steel slate
# slate swan and your if statement isnt indented well
@commands.command(name='Purge')
    @commands.has_permissions(manage_messages=True)
    async def Purge(self, ctx, limit: int):
            if not limit:
                purge_failed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
                purge_failed.set_footer(text=str(datetime.datetime.now()))
                await ctx.channel.send(embed=purge_failed)
        await ctx.message.delete()
        await asyncio.sleep(1)
        await ctx.channel.purge(limit=limit)
        purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
        purge_embed.set_footer(text=str(datetime.datetime.now()))
        await ctx.channel.send(embed=purge_embed)
    @cog_Purge.error
    async def sendback(self, ctx, error: commands.CommandError):
        if isinstance(error, commands.MissingPermissions):
          await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")```
slate swan
#

must be one level in the if statement

#

and return the function

#

so it wont execute everything after it

steel slate
#

wait so how do i set this right

slate swan
#

wdym

steel slate
slate swan
#

you if statement

steel slate
#

that is how code writes it out

slate swan
#

ive said it many times

steel slate
#

oh the if limit:

slate swan
#

yes

#

and dont send the embed like that

#
return await ctx.send(embed=purge_failed)
#

it will return the function^

steel slate
slate swan
#

no need for the other if statement

#

if limit is none it will just return the function and if not it will just continue

steel slate
#

or how do i set the properly

slate swan
#

no the other action you want to do you want it out of the if statement

steel slate
#

can you rewrite it because i don't understand what ya mean

slate swan
#

just delete a level of indentation after the return

steel slate
slate swan
#

yes but no need to do ctx.channel

#

just do ctx.send

#

and you can use the timestamp kwarg in the embed

steel slate
slate swan
slate swan
steel slate
sacred sigil
#

how do I make a member counter text channel? Whenever a member joins (on_member_join event), it updates the channel name to the number of members there are (+ the member that joined)

steel slate
#

let me do tests

slate swan
slate swan
#

^

slate swan
steel slate
slate swan
#

which error

#

oh

slate swan
hoary cargo
#
        async def interaction_check(inter)  :
            if inter.user != inter.author:
                await inter.response.send_message("Just the author can click the buttons.", ephemeral=True)
                return False
            else:
                return True
        await interaction_check(inter)

why the check is not working awhyyy i have some buttons and i want to be clickable just by the author, i have no errors regarding it but just seems ineffective

slate swan
#

because you need to add a defualt value of None @steel slate

#

to the arg

sacred sigil
steel slate
slate swan
#

just pinged a random dude oops sorry

steel slate
#

oopd

craggy cloak
#
@client.event
async def on_message(message):
   channel = client.get_channel(922582463241416756)
   if message.channel.id == channel.id:
       await message.add_reaction('✅')
       await message.add_reaction('❌')

No Error: but the bot isn't adding this reactions?

steel slate
slate swan
#
async def interaction_check(self, interaction: disnake.MessageInteraction) -> bool:
    if interaction.author != self.author:
        return False
    return True

example ^

plain eagle
#

iirc syntax this should be correct?

echo wasp
plain eagle
steel slate
#

or how do i do this?

#

to make it correct

#

i haven't used if statements with none before

hoary cargo
slate swan
steel slate
slate swan
#

in params

steel slate
#

so like this

echo wasp
slate swan
#

i said in parameters

echo wasp
slate swan
unkempt canyonBOT
#

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

arg is None
slate swan
#

discord coding lol

echo wasp
#

lol

#

so how do i write the limit

steel slate
#

like this ?

steel slate
slate swan
#

no no in limit

#

it was an example

steel slate
#

please show me

slate swan
#

limit: int = None

wanton veldt
echo wasp
#

the real vscode

echo wasp
#

right?

slate swan
#

no in parameters

honest vessel
#

he ask for help whole days

#

n dosnt know basic shit

slate swan
slate swan
honest vessel
#

😦 i dont wanna be a bitch but its timeconsuming even try help

slate swan
#

so i got it

honest vessel
#

@slate swanam all for helping but kinda sucks when he dont have the wanna learn n try himself - and if no help, he ask about other commands that dosnt works

#

copypastabot

slate swan
#

if you have the knowledge why not bless someone with it?

honest vessel
slate swan
#

not a big deal

honest vessel
#

or he gonna ask for simplest thing 24/7

slate swan
echo wasp
echo wasp
honest vessel
slate swan
#

@steel slate in the if statement it must be

if not limit

since limit is an argument and in parameters you should add

limit: int = None

which limit expects it to be an integer and has a default value of None

echo wasp
slate swan
#

its alright no need to fight we all know somethings others dont and thats why we help eachother

honest vessel
slate swan
#

@honest vessel stand down please

#

this is a helping channel

honest vessel
#

nah no problemos

steel slate
#

not a coding error

slate swan
#

maskuh forget it

#

can we just stop

honest vessel
#

dont mind me 🙂

steel slate
slate swan
#

the answers to your problem are here

steel slate
honest vessel
#

if not limit: will nvr run

slate swan
#

i got you

honest vessel
#

cause argument missing (parameter)

slate swan
#

you learn like me with examples and thats alright

#

❤️

hoary cargo
# slate swan isnt interaction_check supposed to be in the button class

peepocryyyyyy shut up please, i tried sub-classing the view and buttons , i ended up with something like

 class View4(View):

        @discord.ui.button(label='a', style=discord.ButtonStyle.blurple)
        async def button_callback(self, button, inter):
            await inter.response.edit_message(embed=embed1)

        @discord.ui.button(label='b', style=discord.ButtonStyle.blurple)
        async def button_callback(self, button, inter):
            await inter.response.edit_message(embed=embed2)

        @discord.ui.button(emoji='🗑️', label='Remove Buttons')
        async def button_callback(self, button, inter):
            await inter.response.edit_message(view=None)

the main problem was the embeds so i give up with this ngl

honest vessel
steel slate
#

moved into a dm

slate swan
slate swan
#

name them something differently otherwise they'll override each other

slate swan
# steel slate moved into a dm
@commands.command(name='Purge')
    @commands.has_permissions(manage_messages=True)
    async def Purge(self, ctx, limit: int = None):
            if not limit:
                purge_failed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
                purge_failed.set_footer(text=str(datetime.datetime.now()))
                return await ctx.send(embed=purge_failed)
            await ctx.message.delete()
            await asyncio.sleep(1)
            await ctx.channel.purge(limit=limit)
            purge_embed = discord.Embed(title='Purge [%Purge]', description=f'Successfully Purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
            purge_embed.set_footer(text=str(datetime.datetime.now()))
            await ctx.send(embed=purge_embed)
    @Purge.error
    async def sendback(self, ctx, error: commands.CommandError):
        if isinstance(error, commands.MissingPermissions):
          await ctx.send(f"{ctx.author.mention}You do not have permissions to do this command.")
#

sorry i dont like helping in dmspithink

steel slate
honest vessel
#

@hoary cargo button_a, button_b, would be something since u label has that a, b - for function names

slate swan
slate swan
#

since .purge returns a list of all the deleted messages

#

more accuracy

slate swan
#

:ASakashrug:

#

¯_(ツ)_/¯

#

i keep forgetting i don't have nitro anymore 😔

honest vessel
#

u poor

slate swan
#

:kek: 🥺

real hearth
#

Why is my first event not going?

async def on_message(message):
    if message.author == bot.user:
        return

    if "fdp" in message.content:
        await message.channel.send(
        f'{message.author.name}, qlf man swears at me :(')
        
    await bot.process_commands(message)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if "sorry" in message.content:
        await message.channel.send(
            'ok man, you owe a picture of the dick')

    await bot.process_commands(message)```
slate swan
honest vessel
slate swan
#

¯_(ツ)_/¯

#

hi

#

im new to python

honest vessel
#

should't await bot.process_commands(message) be at top?

#

or is it bottom 🤷🏻‍♂️

slate swan
slate swan
honest vessel
#

yeah def kinda old use that

steel slate
#

so how do i fix that so it works?

slate swan
honest vessel
real hearth
slate swan
steel slate
slate swan
#

but it doesnt overwrite itself on_message

real hearth
slate swan
real hearth
#

thanks**

slate swan
#

yw

real hearth
#

bad here in Brazil there are not many discord bot tutorials...

#

: (

slate swan
#

oof

#

that sucks

real hearth
#

si

slate swan
#

welp i got to go see you guys laterpithink

echo wasp
#

what is the point of sending the command lol

real hearth
honest vessel
jovial storm
#

I'm a beginner, how do you make discord bots wait for a response?

slim ibex
#

discord bot is a bad beginner project

vale wing
jovial storm
vale wing
#

So you know python alright

slim ibex
#

oh well ok

jovial storm
#

ye i guess

vale wing
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/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
jovial storm
#

sorry for not clarifying it

jovial storm
honest vessel
#

check documentation they have example of wait_for()
edit: click that link above ^

flat solstice
#

How long can it take a bot to get the history of a channel? I have it grabbing the history of a channel with 48.8k msgs and whilst i'm assuming it will take a while i'm just wondering if anyone knows a rough time it will take to completeNevermind, it took about 10 mins to do 48,869 msgs so that's 4,886.9 msgs per min, I think

honest vessel
#

😄

#

@flat solstice5k a min not bad?

#

83 msg a sec

#

@flat solsticemore important what api thinks about that?:D

#

aka limits

quaint epoch
#

anyone know what's the request limit on disnake?

echo wasp
#

Ok so with the if command for the welcomer can i do print with the return to make sure it works?

sacred sigil
#

Using a wait_for(), how do I check if the message was either yes or no?

#

for example, if I want confirmation from the executer that they want to run this command, how would I wait for it, and how would I check if it's yes or no

final iron
sacred sigil
#

Creating a delete all messages in a channel command (works by cloning the channel and deleting the last one), how would I go about it?

@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
    channel = ctx.channel
    author = ctx.author

    await ctx.message.delete()
    await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
    ...
#

@final iron

final iron
#

Have you used wait_for() before?

sacred sigil
#

never

final iron
#

Ah

#

Have you checked out the docs?

#

They have examples

#

!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/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
sacred sigil
final iron
#
@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')
#

This is checking content

sacred sigil
#

and what about if it returns a no?

#

I want it to abort the command if its an n or no

#

i dont get it

#
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
    channel = ctx.channel
    author = ctx.author

    await ctx.message.delete()
    await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
    msg = str(bot.wait_for("message"))
final iron
sacred sigil
#

yeah....

final iron
#

So you can check if "yes" is in msg

#

You also need to add a check

sacred sigil
#

i still don't understand the check

final iron
#

Which part?

sacred sigil
#
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
    channel = ctx.channel
    author = ctx.author

    def check(m):
        return m.content == #why am I doing a check if I'm going to do a check for yes or no?

    await ctx.message.delete()
    await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
    msg = str(bot.wait_for("message", check=check))
#

??

final iron
#

You need to define a check (function) and use the check kwarg

sacred sigil
final iron
#

You need to have a check or else any user can say yes

#

And then it will wipe the channel

sacred sigil
#

okk

#

so How do I do this check?

final iron
#

Again, not 100% sure

#

But I think m is a discord.Message object

#

Therefore

sacred sigil
#
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
    channel = ctx.channel
    author = ctx.author

    def check(m):
        return m.author == author
        
    await ctx.message.delete()
    await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
    msg = str(bot.wait_for("message", check=check))
#

like that?

final iron
#

Yup

#

You might want to check if it was the channel the message was run in

sacred sigil
#

okok

final iron
#

But thats your choice

sacred sigil
#

did it

#
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
    channel = ctx.channel
    author = ctx.author

    def check(m):
        return m.author == author and m.channel == channel

    await ctx.message.delete()
    await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
    msg = str(bot.wait_for("message", check=check))

    if msg == "yes" or msg == "y":
        ...
    elif msg == "no" or msg == "n":
        ...
#

like this?

torn sail
#

!or

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
sacred sigil
#

fixed it @torn sail

torn sail
#

Nice

#

Also don’t do str(bot.wait_for). Use msg.content to check what the message says

sacred sigil
#
@bot.command(aliases=["nukechannel", "channelnuke", "n"])
@commands.is_owner()
async def nuke(ctx):
    channel = ctx.channel
    author = ctx.author

    def check(m):
        return m.author == author and m.channel == channel

    await ctx.message.delete()
    await ctx.send(f"are you sure you want to delete all messages in {channel} (**y**/**n**")
    msg = bot.wait_for("message", check=check)

    if msg.content == "yes" or msg.content == "y":
        ...
    elif msg.content == "no" or msg.content == "n":
        ...
flat solstice
#

So I have this command which I've asked a few questions about over the past few days and I thought I'd got it all functional but I've been running it today and it doesn't seem to be sending my embeds but it's also not giving me a error which makes me think it's a logic issue somewhere
https://srcb.in/Us46YHcqyf

slate swan
#

I need help with a piece of code. I am creating a discord bot using python. This is my code:

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('$hello'):
    await message.channel.send('Hello!')

client.run(os.getenv('TOKEN'))```

But instead of saying "Bot Ready!" it gives me this syntax error:

```py
Traceback (most recent call last):
   File "main.py", line 18, in <module>
      client.run(os.getenv('TOKEN'))
peak salmon
#

are there any good libraries with components or should I start learning java?

velvet tinsel
#

why Java?

tacit storm
#

heya so i have a database for my bot setup (mongodb) but im not sure how to get it to get a custom prefix from the database itself?

#

can anyone help?

flat solstice
#

So I have this command which I've asked a few questions about over the past few days and I thought I'd got it all functional but I've been running it today and it doesn't seem to be sending my embeds but it's also not giving me a error which makes me think it's a logic issue somewhere
https://srcb.in/Us46YHcqyf

slate swan
#

i havent done python in so long. how do i get the variable to increase with a command?

tacit storm
#

put it inside the function

#

thats why it's a read line under it

#

other than that, im not sure what else

#

since ive never worked with global variables in discord.py

flat solstice
slate swan
#

thanks

tacit storm
slate swan
#

am I doing smth wrong?

#

here code

#

oh wait nvm

#

sorry i think i figured it out

flat solstice
#

👍

slate swan
#

you call a command as so <prefix_goes_here>command_name

vivid bear
#

in discord.py scripts , in which part of code should i connect postgres db ?
i would need it mostly in some commands and on events like on_message , on_member_update , on_member_join etc.
i m new to db and sql so i need a bit clear info.
Ps : i read+know discord.py docs 💯 %

slate swan
#

make a global var

final iron
slate swan
#

that to

final iron
#

!bot-var

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

bot var is better tbh

final iron
#

If its async then you make it in an async function

slate swan
#

yup

vivid bear
slate swan
#

noooooooooo

#

dont load your db on ready

#

do this

async def startup_function():
    # load db......

#in the bottom of your file create the task
bot.loop.create_task(startup_function())
vivid bear
#

||ok , make a bot variable right
then what to do with conn=psycopg2.connect(params.)
where to be done ?||

vivid bear
#

is this a tasks.loop() process ?

slate swan
#

wdym

#

btw you should add wait_until_ready

#

!d discord.ext.commands.Bot.wait_until_ready

potent spear
unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.
potent spear
#

because you obv want the db to be ready BEFORE the bot goes online

#

no need for wait_until_ready()

slate swan
#

oh yeah we arent changing status sorry

fleet sparrow
#

Hello, im trying this:

    if cmd == 'amount':
        f = open('data.txt', 'r')
        for line in f.readline():
            line = line.rstrip()
            await ctx.send(line)```

for read every line and send it but its sending letter by letter of each line.
slate swan
#

!e

a = "string"
print([b for b in a])
unkempt canyonBOT
#

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

['s', 't', 'r', 'i', 'n', 'g']
slate swan
#

in this case it will send it as a list

#

since its a list comprehension

#

!e

a = "string"
for b in a:
    print(b)
unkempt canyonBOT
#

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

001 | s
002 | t
003 | r
004 | i
005 | n
006 | g
potent spear
#

he probably meant readlines

slate swan
#

by?

fleet sparrow
potent spear
#

well, readline, reads only one line
readlines reads all the lines

vivid bear
#
async def startup_function():
    # load db......
#in the bottom of your file create the task
bot.loop.create_task(startup_function())

ok this will get my db ready ..
then i put some database's data in bot.variable ok!
do i have to connect/close to db in every way? like in on_message , on_member_join , on_xyz
or there is a correct way of doing that 🤔

potent spear
#

closing the db will get trashed automatically once you terminate the bot
but you can overwrite the bot's "close" function if you want to do it explicitly

#

I highly suggest you to make like seperate "help/utils" for every DB function you want to execute, so you can easily reuse them

#

for example

async def all_members(self):
  await self.db.execute("SELECT * FROM members")
  shit = await self.db.fetchall()
  return shit```
This can be a class which you extend your botclass with
potent spear
#

so you can easily call
db_members = await bot.all_members()

potent spear
#

or member: discord.User

slate swan
potent spear
#

equally as bad

slate swan
#

yes

potent spear
#

btw, forget what I said about the cursor, I forgot you don't really need them in an async db, you just straight up execute and fetch from the connection
(check docs for this ofc)

vivid bear
#

ok so to do operations on db i need a ctx manager
and what to do for db not be trashed?

potent spear
potent spear
vivid bear
#

there are .. but they use asyncpg and i m using psycopg2 ... i also a lill bit confused 😐

potent spear
#

well, psycopg2 has docs too 🧠

quaint scaffold
#

You shouldn't use synchronous database adapters for Discord bots

potent spear
#

correct

#

asyncpg is the async wrapper of postgres

vivid bear
#
2) ctx manager
3) psycopg2 docs

i'm gonna work on these 3 tonight.
thanks mates for all the helps 🙂

potent spear
vivid bear
#

Aah okay

slate swan
#

Need help fixing something

#
client.counter = 0

client.this_dict = {}

@client.command(pass_context=True)
async def drink(ctx):
    if (ctx.channel.id == 912562881684471810 or ctx.channel.id == 905601358562996244):
        await ctx.message.delete()
        client.counter += 0.02
        if client.counter >= 0.15:
            await ctx.send(f'You need to rush to the Hospital! {ctx.author.mention}')
        if client.counter >= 0.40:
            await ctx.send(f'You have died! You drank youself to the bottom of the barrel!')
        client.this_dict[ctx.author.id] = client.counter
        await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
        await asyncio.sleep(60*(30))
        client.counter = 0
#

This is apparently mixing up people's counters

#

So if, for example, I do -drink

#

It'll increase to 0.02

potent spear
#

you obviously want a different counter per user

slate swan
#

Umhmm, but i set the author's counter to the dict?

#

shoudnt they all be registered differently?

potent spear
#

nope

#

access the counter like this_dict[user_id]

#

that'll return the counter of that user

#

also, since you're not using a DB, I suppose you don't care if when the bot restarts, data is lost?

slate swan
#

Well, the values resets after 30 minutes anyways so no point of using a data base

potent spear
#

aight

#

anyways, first thing to do in that command is make sure the user has a counter in that dict

#

if he doesn't, add one and set it to 0

slate swan
#
@client.command()
async def checkbac(ctx, *, arg : discord.Member):
    if (ctx.channel.id == 912562881684471810 or ctx.channel.id == 905601358562996244):
        await ctx.message.delete()
        if arg.id not in client.this_dict:
            return await ctx.send(f'{arg.mention} has a Blood Alcohol Concentration Level of: 0.00')
        await ctx.send(f'{arg.mention} has a Blood Alcohol Concentration Level of {client.this_dict[arg.id]}')
        if client.this_dict[arg.id] >= 0.15:
            await ctx.send(f'{arg.mention} needs to be rushed to the Hospital!')
potent spear
#

also, let's shorten it up

slate swan
#

This is to check someone's counter

#

if arg.id not in client.this_dict:
return await ctx.send(f'{arg.mention} has a Blood Alcohol Concentration Level of: 0.00')

potent spear
#

if ctx.channel.id in (912562881684471810, 905601358562996244):

potent spear
#

like user_alcohol_counter = {}

#

and once filled, it should look like

{ 123456: 0,
  155151: 0.5
}```
slate swan
#

I'm a little confused by what you mean?

slate swan
potent spear
slate swan
potent spear
#

no, just only use the bot.counter_dict

#

or whatever that dict is

#

you don't need the bot.counter, since everyone can access that...

#

do when you drink, it sohuld should look like
client.counter_dict[ctx.author.id] += 0.05

#

or whatever your values are

slate swan
potent spear
#

idk lol ,you count them with .15 sometimes lol

slate swan
slate swan
potent spear
slate swan
slate swan
# potent spear yeah, just only count PER user, as said earlier
client.counter = 0

client.this_dict = {}

@client.command(pass_context=True)
async def drink(ctx):
    if (ctx.channel.id == 912562881684471810 or ctx.channel.id == 905601358562996244):
        await ctx.message.delete()
        client.counter += 0.02
        if client.counter >= 0.15:
            await ctx.send(f'You need to rush to the Hospital! {ctx.author.mention}')
        if client.counter >= 0.40:
            await ctx.send(f'You have died! You drank youself to the bottom of the barrel!')
        client.this_dict[ctx.author.id] = client.counter
        await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
        await asyncio.sleep(60*(30))
        client.counter = 0

Shouldnt the counter reset bc of client.counter = 0 at the end?

slate swan
#

I'm doing that as well, but thinking about the logic, shouldnt the counter reset?

potent spear
#

that's how you would reset the counter FOR THAT USER

slate swan
#

Welp, I am a total dumbass. I understand now

potent spear
#

actually deleting the value might be a better idea, since you don't want hundreds of key values where the counter is just 0, only add them if it's not 0 or whatever

#

also, check out "command checks", this is basically a replacement of your outer if statement

potent spear
#

or even better

#

use cogs (this categorizes commands, tasks and events), and use a cog check
that way, you don't have to use a command check for every command
since I suppose you can only run certain commands in the same 2 channels

slate swan
potent spear
#

code?

slate swan
#
@client.command(pass_context=True)
async def drink(ctx):
    if ctx.channel.id in (912562881684471810, 905601358562996244):
        await ctx.message.delete()
        client.this_dict += 0.02
        if client.this_dict[ctx.author.id] >= 0.15:
            await ctx.send(f'You need to rush to the Hospital! {ctx.author.mention}')
        if client.this_dict[ctx.author.id] >= 0.40:
            await ctx.send(f'You have died! You drank youself to the bottom of the barrel!')
        #client.this_dict[ctx.author.id] = client.counter
        await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.this_dict[ctx.author.id]}')
        await asyncio.sleep(60*(30))
        client.this_dict[ctx.author.id] = 0
#

crap

#

ik how to fix 1 sec

potent spear
#

client.this_dict += 0.02
this is ofc the problem

quaint scaffold
#

You can remove pass_context=True

#

This was necessary a few years ago when discord.py was created, not anymore

slate swan
potent spear
#

make sure the key is in there before adding shit to it ofc

slate swan
#

Yea adding an if statement that will set the user's number to 0 before doing the command

slate swan
potent spear
slate swan
potent spear
#

I'd do like:
if drank too much, remove from dict
if he uses the drink command again
if not in this_dict, then this_dict[author.id] = 0.02

#

since the first drink, he has 0.2 apparently

#

then, if you want to check someone's alcohol level
if he's not in the dict => his alcohol level is 0
else: do other shit

#

also, use elif
you're also literally resetting someone's alcohol lvl after every drink

pliant gulch
#

You can do client.this_dict.get(arg.id, 0) then send that as the current BAC

#

Thus allowing for a default value if arg.id does not exist in the dict

potent spear
royal oar
#

Hello! i am trying to make a rob commands but i cannot not get it to send the messages can you guys please help me. There is no error showing.

@commands.command()
    async def rob(self,ctx,member:nextcord.Member):
        await open_account(ctx.author)
        await open_account(member)
        
        bal = await update_bank(member)
        authorBal = await update_bank(ctx.author)

        if bal[1]<5000:
            await ctx.send("No point robbing this one, sweet child <3, leave them be them be they are saving up, and they dont have $5000 ;-;")
            return
        if authorBal[1]<5000:
            await ctx.send("No point robbing you dont have $5000 ;-;")
            return
        earnings = random.randrange(20, bal[0])
        bad_luck = random.randrange(20, authorBal[0])
        Truth = []
        c = random.choice[earnings, bad_luck]
        Truth.append(c)

        if Truth[earnings]:
            await update_bank(ctx.author,earnings)
            await update_bank(member,-1*earnings)
            await ctx.send(f"You stole ${earnings}, Lets hope they dont want revenge")
        if Truth[bad_luck]:
            await update_bank(ctx.author,-1*bad_luck)
            await update_bank(member,bad_luck)
            await ctx.send(f"You lost ${bad_luck}, teaches you right")
slim ibex
#

where does the issue occur

#

oh wait no error shows

royal oar
#

indeed

quaint scaffold
#

Is it entering the if statements?

royal oar
#

i dont think so

quaint scaffold
#

There's your issue

royal oar
#

But i dont know how to fix that?

slim ibex
#

your if statements are unreachable

royal oar
#

how do i make them reachable? sorry for the dumb questions

potent spear
#

don't follow stinky YT tutorials first of all

slim ibex
#

^

royal oar
#

Half of that came from tutorial

#

I added the lists to choose between earnings and badluck

#

the if statesment become unreachable

quaint scaffold
#

For example, if you followed half of what freecodecamp tutorials said, you'd be fucked.

royal oar
#

I followed this one fully

#

i added my own code to it

quaint scaffold
royal oar
#

to try and make the money go into the oppiste account

royal oar
quaint scaffold
#

That means you don't understand what you are doing

slim ibex
#

its an issue with your code

quaint scaffold
#

What are you trying to do below the randranges

slim ibex
#

that you added

royal oar
#

and added to another

quaint scaffold
#

What is Truth and bad_luck

royal oar
#

Bad luck takes the balance out of the robber.
the truth variable chooses between the earnings and badluck

it chooses the path for the robber

#

whether it fails

#

or it succeeds

potent spear
#

terrible varnames, sorry xd

royal oar
#

ik

quaint scaffold
#

Yeah, your code is very unreadable so it makes helping quite difficult. But what you are doing in the if statement is indexing a value from 20-5000+. It'll raise an indexerror

royal oar
#

but wouldnt it send an error of thats the case?

quaint scaffold
#

Yes

#

!e py l = [2863] if l[2863]: print('hi')

unkempt canyonBOT
#

@quaint scaffold :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: list index out of range
quaint scaffold
#

Not sure why you don't see any errors

royal oar
#

that what im confused about

royal oar
quaint scaffold
#

Just use a tuple when you make the randrange

kindred epoch
#

Is there a way I can make my bot check if a user used a certain slash command from a different bot?

potent spear
slate swan
#

on_message would detect the message sent by other bot on using the command , but not the invocation message from user

#

doesnt detect the /ping , but detects the response from bot

#

idk about other libraries but Disnake (or mb discord.py itself) has Message.interaction to check if message was created with some interactions
Message.interaction.type will return application_command if it was sent in response to a slash cmd

echo wasp
#

So how do you print perms it has for each guild on startup?