#discord-bots

1 messages ยท Page 467 of 1

lofty mulch
#

I'm opening Vscode, brb

hasty iron
#

why do you even need self.bot.cogs

#

you only need self.bot.get_cog

waxen granite
#

i dont understand, how will get the cogs then?

lofty mulch
#

Yeah, it doesn't show any errors

hasty iron
hasty iron
lyric moat
#

how do i do buttons command?

lofty mulch
#

I did, I pretty much do Ctrl + S every few seconds

waxen granite
#

i am trying if cogname == anyone of the cogs

lofty mulch
#

I learned my lesson after crashing Vscode

hasty iron
#

as i said, bot.cogs is a mapping of the cog name and the cog itself

#

you only need to check the name

pliant gulch
#

If you just want to see if a cog exists use get_cog and the walrus operator

#
if cog := bot.get_cog("name"):
    # cog exists
#

Keep in mind walrus operator in python 3.8^

lofty mulch
#

Yep, doesn't really show anything

hasty iron
#

Python?

lofty mulch
#

Yep

hasty iron
#

use what andy said

lofty mulch
#

It's the way to execute a file through the terminal

hasty iron
#

its better

lofty mulch
#

That works for me, atleast

hasty iron
#

windows doesnโ€™t have python

#

it has py

lofty mulch
#

It still works when i doPython File.py

waxen granite
#

i am not doing it for jsut one cog

lofty mulch
#

I'm not sure why, it just works like that

slate swan
#

can someone explain why I keep getting this?

  File "/home/turtle/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/turtle/dusk-beta/cogs/economy.py", line 423, in baltop
    print(doc['net'])
TypeError: 'int' object is not subscriptable```
hasty iron
hasty iron
#

anything outside the cog class

waxen granite
#

well in my bot there are many cogs, i am trying to cogname == any one of the cog then get it commands and limit them.

lofty mulch
#

Nothing other than declarations and the def setup

pliant gulch
#

Yeah? Use my example and instead of a string pass a variable to get_cog

lofty mulch
#

I'm considering just rewriting the whole main.py, it's been giving me problems since forever

hasty iron
#

actually

pliant gulch
#

And since it's in a walrus you get the cog obj if it isn't none

hasty iron
#

the issue could still be from that cog file you imported at the top

#

can you send its code

slate swan
hasty iron
#

you tell me, itโ€™s your code not mine

slate swan
#

that's why i'm trying to print it to find out lol

lofty mulch
#

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

slate swan
#

it should be an int

hasty iron
#

okay and doc is an int

cloud dawn
#

you can always check with type()

slate swan
lofty mulch
pliant gulch
#

Why do you need to check the type

#

The error already says it's an int

slate swan
cloud dawn
pliant gulch
#

You can print out an int, you can't try to index on it though

slate swan
hasty iron
hasty iron
patent lark
#

hm.

lofty mulch
#

I might just rewrite

hasty iron
#

actually what about that Imports is it actually commented

lofty mulch
#

This is getting ridiculous, it's been giving me problems since forever

#

It is, I just didn't copy it properly

slate swan
#

no setup function?

#

did I get something wrong?

hasty iron
#

anyways the problem could be from Python

lofty mulch
hasty iron
#

from what i know, its only available if you install from windows store, which is basically a bad version of python

lofty mulch
#

Jesus help me

hasty iron
#

try py?

lofty mulch
#

k

agile dome
lofty mulch
#

Enlightenment

slate swan
#

and I see an uppercase Self

#

which isn't good either
nvm

hasty iron
#

wiat

#

i think i see it

#

load_extension imports the cog

lofty mulch
#

Yep, py doesn't work

hasty iron
#

and inside your cog file, you instantiate a Bot instance

agile dome
hasty iron
#

and that overrides your other instance i think?

lofty mulch
hasty iron
#

well im not actually sure anymore

edgy fractal
#

Only one image shows up...

invinfo.set_thumbnail(url=f"https://cdn.discordapp.com/banners/{r['id']}/{r['icon']}.png")
            invinfo.add_field(name='Server ID', value=r['id'])
            invinfo.set_image(url=f"https://cdn.discordapp.com/banners/{r['id']}/{r['banner']}.png?size=1024")
hasty iron
#

im just guessing at this point

cloud dawn
hasty iron
agile dome
edgy fractal
cloud dawn
slate swan
#

!e

@client.event
async def on_member_join(member):
  channel = client.get_channel(880455561899044975)
  embed = discord.Embed(title="๐Ÿ‘‹Bem-vindo(a)!", description=f"Olรก {member.mention}, espero que vocรช se divirta no meu servidor!", color=0x850dbd)
  embed.add_field(name="โ›”๏ธ Precisa de alguma ajuda", value="Caso necessite de alguma ajuda da STAFF, abra um ticket #ticket", inline=False)
  embed.add_field(name="๐Ÿ‘ฎ Evite Puniรงรตes", value="Leia as nossas @pale sky", inline=False)
  embed.set_author(name=member.name, icon_url=member.avatar_url)
  embed.set_thumbnail(url=member.avatar_url)
  embed.set_image(url="https://i.imgur.com/1ajH1RF.gif")
  embed.set_footer(text=f"ID: {member.id}")
  
  await channel.send(embed=embed)
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'client' is not defined
agile dome
cloud dawn
hasty iron
#

its not dead

#

its still very usable

oak quest
#

do you guys know any good api for pokemon or digimon ?
that could give all of the information about the characters ?
i searched but didn't found what i wanted

slate swan
#

!e

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members=True
client = commands.Bot(command_prefix = "!", case_insensitive = True, intents=intents)

@client.event
async def on_member_join(member):
  channel = client.get_channel(880455561899044975)
  embed = discord.Embed(title="๐Ÿ‘‹Bem-vindo(a)!", description=f"Olรก {member.mention}, espero que vocรช se divirta no meu servidor!", color=0x850dbd)
  embed.add_field(name="โ›”๏ธ Precisa de alguma ajuda", value="Caso necessite de alguma ajuda da STAFF, abra um ticket #ticket", inline=False)
  embed.add_field(name="๐Ÿ‘ฎ Evite Puniรงรตes", value="Leia as nossas @pale sky", inline=False)
  embed.set_author(name=member.name, icon_url=member.avatar_url)
  embed.set_thumbnail(url=member.avatar_url)
  embed.set_image(url="https://i.imgur.com/1ajH1RF.gif")
  embed.set_footer(text=f"ID: {member.id}")
  
  await channel.send(embed=embed)
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
pliant gulch
#

inb4 discord makes breaking changes

hasty iron
pliant gulch
#

Wouldn't be surprised anyhow

hasty iron
#

i used it before

pliant gulch
cloud dawn
slate swan
#

eval?

hasty iron
#

evaluation

#

that command you just tried to execute

lofty mulch
#

no fucking way

#

it actually worked

hasty iron
#

lmao

lofty mulch
#

blanket your brain is so big, jesus

oak quest
lofty mulch
#

I love you, seriously

pliant gulch
hasty iron
#

are you looking for the trading card game version?

oak quest
#

i found an api earlier but i forgot the domain

oak quest
#

i'm making a gacha bot

hasty iron
#

ah

pliant gulch
#

Look in your search history

#

If you alr found it

lofty mulch
#

and it got stuck on the loading

oak quest
pliant gulch
#

I'd rather not

oak quest
#

there are alot of pages

oak quest
hasty iron
lofty mulch
#

lmao I can already see how bad it's going to get when I get an internship as a JSE

agile dome
oak quest
#

do you guys know any api for yugioh - shadowverse - digimon - gundam ?
but with card iamges

hasty iron
#

no, there is a search bar

lofty mulch
# oak quest what ?

I've spent the last three days trying to fix random errors from my Main file

#

And when it finally seems like I fixed it

#

Another one immediately appears

oak quest
#

i think i found it

#

pokemon tcg

agile dome
#

@lofty mulch do u know heruko cuz i know how to host the bot

#

24/7

lofty mulch
#

I don't plan on hosting it

agile dome
hasty iron
#

its literally the first result of "tcg pokemon api"

oak quest
lofty mulch
#

๐Ÿฆ€ It worked ๐Ÿฆ€

#

Thanks blanket, you're truly a life-saver

hasty iron
#

np

pliant gulch
# oak quest ?

Thats what google is for, this channel isn't your personal search engine

#

And anyhow out of the scope for this channel

oak quest
hasty iron
#

make your own api then

vale root
#

How Do I make my snipe bot put the person being sniped's avatar as a embed.set_thumbnail

#


@commands.command(name="Snipe")
    async def snipe(self, ctx: commands.Context):
        if not self.last_msg:
            await ctx.send("There is no message to Snipe!")
            return

        author = self.last_msg.author
        content = self.last_msg.content

        embed = discord.Embed(title=f" Message from {author}", description=content)
        await ctx.send(embed=embed)
oak quest
hasty iron
#

you could find a database of images

waxen granite
#

doing {', '.join(cmdList)} for cmdList = cog.get_commands()
should get all cmds like cmd1, cmd2, ... right?

cloud dawn
waxen granite
#

doing in a fstring

cloud dawn
#

Well yeah this should be fine but cmdlist does need to be a list of strings and now it's a list of command objects

#
cmdList = [cmd.name for cmd in cog.get_commands()]
vocal cargo
#

@client.event
async def on_message(ctx):
if ctx.content.content('poop'):
ctx.channel.send('poop')

#

in on_message
if ctx.content.content('poop'):
AttributeError: 'str' object has no attribute 'content'

#

anyone know how to fix

slate swan
#

whats the content of the content

cloud dawn
#

hmm

waxen granite
#

ctx.message.content

vocal cargo
#

i want it whenever it says "poop" it replies with "poop"

#

obv just an example word for now

jade oxide
#

on_message

#

use the message parm

vocal cargo
#

what does that mean

slate swan
#

thats convention

vocal cargo
#

what would i put for that

waxen granite
#

if "poop" in message.content:
await message.reply("poop")

vocal cargo
#

thanks

jade oxide
#

^

cloud dawn
#

And change ctx to message inside the function.

vocal cargo
#

yeah that worked

vale root
#

How Do I make my snipe bot put the person being sniped's avatar as a embed.set_thumbnail

@commands.command(name="Snipe")
    async def snipe(self, ctx: commands.Context):
        if not self.last_msg:
            await ctx.send("There is no message to Snipe!")
            return

        author = self.last_msg.author
        content = self.last_msg.content

        embed = discord.Embed(title=f" Message from {author}", description=content)
        await ctx.send(embed=embed)
lofty mulch
#

Is there a way to make the code update itself in real time?

#

It's kinda annoying to keep restarting the code to deploy changes

cloud dawn
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
slate swan
#

does this still work if the cog uses global variables that are in the main file?

vocal cargo
#

async def on_message(ctx):
if ("poop","POOP") in ctx.content:
await ctx.reply('hi')
it doesn't work with more than 1 variable

#

can i not do that?

#

TypeError: 'in <string>' requires string as left operand, not tuple

slate swan
#

no

vocal cargo
#

oh

slate swan
#

if ctx.content in ['poop', 'POOP']

waxen granite
vocal cargo
#

can i not make an array

waxen granite
#

or you can just a list

vocal cargo
#

[

waxen granite
#

or just do this

cloud dawn
vocal cargo
#

what if i want to do more than just spelling

#

how can i make a list/array

slate swan
#

if ctx.content in ['poop', 'POOP']

#

that is an array

vocal cargo
#

kk thanks

cloud dawn
#

Thats a list

vocal cargo
#

i thought brackets worked

lofty mulch
waxen granite
#

and why are you doing ctx.content in on_message event? @vocal cargo

waxen granite
vocal cargo
#

should i be using something else

lofty mulch
#

Welp

tame nymph
cloud dawn
hasty iron
slate swan
#

because htye are all strings

vocal cargo
#

TypeError: 'in <string>' requires string as left operand, not list

tame nymph
vocal cargo
#

the [] didn't work

cloud dawn
slate swan
#

oh

lofty mulch
tame nymph
# vocal cargo the [] didn't work

replace your entire event with

@client.listen()
async def on_message(msg):
  _list = ["poop"]
  if any([i in msg.content for i in _list]):
     await msg.reply("hi")
slate swan
#

what is that underscore for

lofty mulch
#

Thing is, it's pretty annoying to keep reloading it and sometimes the terminal just freezes, forcing me to restart the window

vocal cargo
#

whats the point of the underscore

tame nymph
slate swan
#

so that you dont overwrite the data type

hasty iron
#

you could use

cloud dawn
hasty iron
#

!d importlib.reload

unkempt canyonBOT
#

importlib.reload(module)```
Reload a previously imported *module*. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in [`sys.modules`](https://docs.python.org/3.10/library/sys.html#sys.modules "sys.modules")).

When [`reload()`](https://docs.python.org/3.10/library/importlib.html#importlib.reload "importlib.reload") is executed:
hasty iron
#

but it can cause you probelms

tame nymph
lofty mulch
#

Which type of problems

slate swan
#

ok

vocal cargo
#

thanks

slate swan
#

but it also makes it private

hasty iron
#

for example, your bot.run needs to be inside an if __name__ == "__main__" block

pliant gulch
#

Leading underscores are for not overwriting, if it starts with an underscore that means its a private var

#

If you intend to follow pep8 don't get those two mixed up

tame nymph
pliant gulch
#

No its just a convention

tame nymph
#

how about protected

pliant gulch
#

There is not really a true private variable in python

tame nymph
cloud dawn
#

underscore is just meant to let other programmers know not to mess with that function or variable.

hasty iron
#

you could make it __var

tame nymph
#

cmd._buckets._cooldown.per moment

hasty iron
#

!e ```py
class Obj:
__a = 5

print(Obj.__a)

unkempt canyonBOT
#

@hasty iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | AttributeError: type object 'Obj' has no attribute '__a'
tame nymph
#

!e

class Obj:
  @property
  def __a(self):
    return 5
print(Obj.__a)
unkempt canyonBOT
#

@tame nymph :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | AttributeError: type object 'Obj' has no attribute '__a'
lofty mulch
#

Or is it going to strain my system?

cloud dawn
#

Don't reload if you don't need to reload

pliant gulch
#

Mangling isn't meant for private variables still

tame nymph
#

u can do

async def on_message(msg):
  match msg.author.id:
    case YOUR_ID_HERE:
      #do something
    case _:
      return
pliant gulch
#

That would be if your using python 3.10

tame nymph
#

everyone is

pliant gulch
#

Not everyone has switched to python 3.10

#

Its still very much new

tame nymph
#

everyone excluding everyone

#

better?

cloud dawn
#

Almost no one has python 3.10 running in it's bot.

pliant gulch
#

Matter fact, 3.10 is still in beta iirc

cloud dawn
#

Yep

hasty iron
#

3.10 didnโ€™t work with my sphinx sadge

pliant gulch
#

sphinx

tame nymph
slate swan
#

๐Ÿคจ

hasty iron
#

why did it do that

#

well whatever, sphinx is better than mkdocs

pliant gulch
#

nah

#

rst formatting is just not it

hasty iron
#

well maybe i have spent 900 lines just writing .. autoclass:: but who cares

pliant gulch
#

My point exactly

hasty iron
#

but sphinx actually read my pyx files

pliant gulch
#

But with mkdocs you don't need pyx files

#

Oh wait you meant for cython

hasty iron
#

yes

pliant gulch
#

I thought you mean stubs for a sec

#

lmao

slate swan
#

instead of doing bot.add_cog() for every class, is there a way that i can register every cog in my code in 1 line

brisk fiber
#

you can put the name of every cog in a list, then iterate through that list and do bot.add_cog(item) for each item in the list

#

!d str.lower

unkempt canyonBOT
#

str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3.10/library/stdtypes.html#id15) converted to lowercase.

The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
brisk fiber
#

make it all lowercase first ^

slate swan
#

if msg.lower().startswith('dadadada'):
await message.channel.send('DADADADADADADDADADADADADADADADADADDDADADADADADDADADA!')

#

or lower

#

idk

lofty mulch
#

anyone got some documentation on buckettype?

#

wanna read more about them

plain birch
#

!py

#

!pypi

unkempt canyonBOT
#
Missing required argument

package

lofty mulch
#

!py buckettype

#

huh

brisk fiber
#

rip

plain birch
#

what is the symbol to send a python coder in here?

lofty mulch
#

`

#

actually, `*

#
print ('Hello, world!')
#
print ('Hello, world!')
#

huh, ok then

plain birch
#

doesnt work...

lofty mulch
#

it does

#
X = 5 
Y = 5/2

print (Y)
vernal remnant
#

why do you have a space after print?

#

should be togethet print(y)

final iron
#

It's !e I think

lofty mulch
#

I like to keep stuff tidy and pretty

final iron
#

For the bot

lofty mulch
vernal remnant
#

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

lofty mulch
#

Makes me feel like I didn't pay enough attention to the code and it's going to fail and explode

vernal remnant
brisk fiber
#

is there something like on_error() for cog listeners (not just the base events)?

lofty mulch
#

Like, an errorhandle?

brisk fiber
#

yeah

#

so i don't have to repeat my desired default error handling code in each listener

lofty mulch
#

You can build a class for that and form a global handler

#

if that's what you wanted

orchid salmon
#

Does anyone know how to embed an image created in memory?

blank = Image.new("RGB", (1280, 720), (30, 30, 30))

em = discord.Embed(title="TEST", color=COLOR_DEF)
em.set_image(blank)
await ctx.message.reply(embed=em)
brisk fiber
#

good idea though, i'll look into it

lofty mulch
#

class ErrorHandle(commands.Cog):
  def __init__(self, bot):
    self.bot = bot

  @commands.cog.listener()
  async def On_Command_Error(yada yada yada, stuff)
#

And not that I know off

#

you gotta build your own handler

brisk fiber
#

i have some listeners as well

lofty mulch
#

ooooh, for listeners?

brisk fiber
lofty mulch
#

lemme see what I can find for ya

brisk fiber
#

!d discord.on_error

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.9)").

If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.9)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client").
brisk fiber
#

this only handles the various on_x events, not their equivalent listeners

lofty mulch
#

Actively search for those permissions and ignore the rest

#

Although I'm not entirely sure on how viable this would be

high flame
lofty mulch
#

Yep, couldn't find much on the listener handles @brisk fiber

#

But yeah

vernal remnant
#

I'm a big newbie but wouldn't you use a try: block to handle errors?

brisk fiber
brisk fiber
vernal remnant
#

ah

brisk fiber
#

no bananas for now though so i'll poke around

lofty mulch
#

I want a banana, I'm quite hungry after all this bug hunting

hollow agate
#
@client.event
async def on_message_delete(message):
    time = datetime.now(tz=pytz.timezone('America/Tijuana'))
    formatted = time.strftime("%I:%M %p")
    logchannel = client.get_channel(872911089258598421)
    await logchannel.send(f'[`{formatted}`] Message by {message.author} `({message.author.id})` in {message.channel.mention} has been removed. \n**Content**: {message.content}')``` How could I get time the message was deleted, then subtract the current time from it to give me how long ago the message was in the channel for before it was deleted?
brisk fiber
#

!d discord.Message.created_at

unkempt canyonBOT
brisk fiber
#

that ^ can tell you when the message was created, and then you can get the current time and subtract

#

i think you can subtract two datetime objects? not sure

lofty mulch
#

If I created a class within my Main file, would it still be readed normally?

#

Kinda curious on this one

brisk fiber
#

like a cog?

lofty mulch
#

Actually, yeah

#

Like a cog

brisk fiber
#

hm not sure

lofty mulch
#

I'm going to create a cog to load a cog

#

๐Ÿง 

brisk fiber
#

i guess if you defined setup() underneath your cog and did bot.add_cog(MyCog), that could work? but i'm not sure you could load it in because bot.load_extension expects a file

#

you could put the cog in a different file though

lofty mulch
#

What I went

#

What if I went*

#

Bot.load_extension(loader)

#

and just created a Cog dedicated to loading another cogs

#

Although that kinda sounds like extra work, it would allow me to clear my main and also easily reload/rewrite in case something goes awfully wrong

acoustic ermine
#

Why not just write some code in the main to load cogs?

hollow agate
#
  File "c:\Users\jacob\OneDrive\Desktop\Code\Camilla\main.py", line 569, in on_message_delete
    msgtime = (formatted - message.created_at).total_seconds()
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'``` Code: ```py
@client.event
async def on_message_delete(message):
    time = datetime.now(tz=pytz.timezone('America/Tijuana'))
    formatted = time.strftime("%I:%M %p")
    msgtime = (formatted - message.created_at).total_seconds()
    logchannel = client.get_channel(872911089258598421)
    await logchannel.send(f'[`{formatted}`] Message by {message.author} `({message.author.id})` in {message.channel.mention} has been removed. \n**Content**: {message.content} \n \n \n{msgtime}')```
#

Not sure what I'm doing wrong here :P

brisk fiber
#

i have a command in my DevCmds cog that lets me reload a cog after making changes, it's pretty useful

#

probably difficult to do it in your main file though

lofty mulch
acoustic ermine
lofty mulch
#

I might just try to code it too

brisk fiber
slate swan
#

Hello does anyone know how to create a dashboard website for a bot?

acoustic ermine
#

I have a reload command took 4 lines lmao

brisk fiber
#

same

slate swan
#

yo ray

#

Do you know how to make a dashboard website for a bot

acoustic ermine
#

With flask?

brisk fiber
#

no i just meant that it'd be unorganized and they were suggesting putting a cog in their main file (i think?)

#

which would be complicated

slate swan
acoustic ermine
#

You could use flask ig

#

But this is a discord bot related channel so letโ€™s stay on topic

brisk fiber
# lofty mulch Want to share it?
    @commands.command(aliases=['reload', 'reloadcog'])
    async def reloadext(self, ctx: commands.Context, cog_to_reload: str):

        try:
            self.bot.reload_extension(f'cogs.{cog_to_reload}')
            await ctx.send(f'Reloaded {cog_to_reload}!')
            print(f'\nReloaded extension {cog_to_reload}')
        except Exception as e:
            await ctx.send(f'Something went wrong: {e}')

(my cogs are stored within a cogs folder) (also yes i should probably move my error handler to an on_command_error this is just legacy code and not meant for widespread use)

slate swan
#

i asked a question

#

lol

acoustic ermine
#

In python

#

And you may also use html with it

acoustic ermine
#

Just jk

brisk fiber
#

also they seem to know what they're doing at least somewhat

acoustic ermine
#

True

lofty mulch
brisk fiber
#

no worries but try to read through it and understand it!

#

so you can do it for yourself next time

lofty mulch
#

I might actually try to create a cog dedicated to dev commands too

acoustic ermine
brisk fiber
#

yeah i'd recommend that

lofty mulch
#

That's also going to save me lots of trouble while testing

brisk fiber
acoustic ermine
#

Ye well with the rewrites version

#

Idk if your on that one

brisk fiber
#

dpy 2.0? or a fork

#

i'm on 2.0 but i haven't updated for a month or two

acoustic ermine
brisk fiber
#

ah sweet

acoustic ermine
brisk fiber
#

oh that doesn't make sense then actually bc my IDE didn't give me all the popup details until i typehinted it and i've never been on anything below 1.7

#

oh well gtg now

lofty mulch
#

Vscode crashed, yay

acoustic ermine
#

Damn

valid niche
lofty mulch
#

Damn

#

Seems like Vscode really died

#

Now It won't open

#

my IDE really went under with casket and flowers

slate swan
#

i need a website dec

pliant gulch
slate swan
#

devvv

blazing coral
#

so i need a bot to do notifications when i upload a video and i want my bot to do it but don't even have a clue were to start with that type of thing as its not something i have done before if anyone wouldn't care to help me out on the key words etc for that it would be great

hollow agate
#
@client.event
async def on_message_delete(message):
    time = datetime.now(tz=pytz.timezone('America/Tijuana'))
    formatted = time.strftime("%I:%M %p")
    msgtime = (formatted - message.created_at).total_seconds()
    logchannel = client.get_channel(872911089258598421)
    await logchannel.send(f'[`{formatted}`] Message by {message.author} `({message.author.id})` in {message.channel.mention} has been removed. \n**Content**: {message.content} \n \n \n{msgtime}')``` How could I make this work? Error: ```py
Ignoring exception in on_message_delete
Traceback (most recent call last):
  File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\client.py", line 351, in _run_event    
    await coro(*args, **kwargs)
  File "c:\Users\jacob\OneDrive\Desktop\Code\Camilla\main.py", line 569, in on_message_delete
    msgtime = (formatted - message.created_at).total_seconds()
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'```
acoustic ermine
valid niche
hollow agate
#

Yeah, how can I make that not a string?

valid niche
#

You did string - datetime

valid niche
#

Which literally stands for string formatted time

hollow agate
#

xd, yeah

valid niche
#

Strftime literally makes a string in the format you want

pliant gulch
#

Why are you mixing time and datetime module??

#

You should just use one or the other

valid niche
#

^

#

I generally always use datetime (only use time for time.sleep)

crude crater
#

someone pls help with a blacklisted words script this shits hard no cap

open forge
open forge
boreal ravine
#

@crude crater ..

crude crater
open forge
#

You can fiddle around with regexes, or for a more basic boilerplate you can just list down the word and some bypasses to check every message for.

#

It's not going to replace the need for chat mods sadly.

pliant gulch
#

I think you are looking at this in the wrong way, It would be better to moderate people who say the N word rather then delete it everytime it is said

#

If it was a blacklist people would try to bypass, if it was being moderated by users then people would probably stay away from saying it

crude crater
open forge
#

No discord bot is going to be as adaptable and intelligent to moderation as a human will be.

#

If you've ever played Roblox, even the filter there gets bypassed. It's almost impossible to make it perfect.

#

Arguably impossible.

#

Besides what you've heard already there's not much else.

pliant gulch
#

Anti spam and blacklists barely work due to how many unicode characters exists

#

I could spam some zalgo characters and your blacklist would fail

#

But hey, if you want to learn something like machine learning for this I guess that might work

lofty mulch
open forge
#

AI-powered word filter would be interesting to see on a bot.

lofty mulch
#

Active-searching list for a word filter?

pliant gulch
#

That would take quite a lot of work

#

I'd imagine tokenizing words with unicode characters would be challenging as well

#

Which is how I'd assume you parse the text

open forge
lofty mulch
#

Unreasonable amount of work, I would just prefer to leave that for mods

open forge
#

Already an AI culture from FB I guess

lofty mulch
#

Although, can't we try to code an AI to actively search for new slurs/bad words?

#

It doesn't sound too bad

#

But surely lots of work

open forge
#

Well it's a prospect that Facebook has only pulled off a 60% success rate with

#

So,

#

Good luck kek

pliant gulch
#

Facebook a billion dollar company only has a 60% success

#

I'd guess that tells you how fruitless this is

lofty mulch
open forge
#

Interesting

#

You can double check what the AI made a verdict on

blazing coral
#

can some tell me what wrong here

#

@client.event
async def on_message_edit(message):
logchannel = client.get_channel(886651843051155497)

await logchannel.send(f'message by {message.author} ({message.author.id}) in {message.channel.mention} has been edited. \nContent: {message.content} new message. \nContent: {new.message.content} ')
#

here is the error it gave

#

Bot is ready.
Ignoring exception in on_message_edit
Traceback (most recent call last):
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_message_edit() takes 1 positional argument but 2 were given

paper bane
#

on_message_edit passes 2 Message objects being the old message and new message accordingly. In your event handler you only have one of them stated

blazing coral
#

i have both stated

#

\nContent: {message.content} new message. \nContent: {new.message.content} ')

#

the terms for it may not be correct

paper bane
#

new is undefined. To state them both you need to have them as parameters in your event function

async def on_message_edit(message):
async def on_message_edit(old, new):
#

That way, you can use both the old and new messages

blazing coral
#

got you okay cool thanks

paper bane
#

anytime

orchid salmon
#

Does anyone know how to get this data from discord.py?

slate swan
#
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
        print('Bot is Ready.')

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

client.run('token here i know')```
#

help me

supple thorn
#

whats the problem?

slate swan
#

it wont run

#

like wont clear the messages

#

when i do !clear

vagrant brook
#

Are you sure the bot has enough permissions

short axle
#

im having issues with import name process player from discord.voice_client can someone help me

pliant gulch
#

You have not typehinted the amount parameter so it is a str rather then an int

#

And the limit kwarg of purge takes an int

#

Make sure to typehint int

hot cobalt
#

Also you named the param ammount

slate swan
hot cobalt
#

Rather than amount

slate swan
#

typeo lol

hot cobalt
#

So limit=amount would throw an error as amount isn't defined

wispy spade
burnt harbor
slate swan
#

i barely know what yall are talking about im new to coding, ive coded one bot but im working on this one

#

ah the #

slate swan
wispy spade
burnt harbor
wispy spade
slate swan
#

thats the code to make the bot leave and join so yah

#

hm it gives me errors

burnt harbor
#

Show the errors

slate swan
#

Traceback (most recent call last):
File "c:\Users\myname"\Desktop\Discord bot\Steve.py", line 18, in <module>
client.run('the token')
File "C:\Users\myname"\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\myname"\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\myname"\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\myname"n\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000203D5AF5AF0>
Traceback (most recent call last):
File "C:\Users\myname"\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\myname"\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\myname"\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users"myname"\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Discord Developer Portal

Integrate your service with Discord โ€” whether it's a bot or a game or whatever your wildest imagination can come up with.

drifting arrow
#

Hey, when I am ready to publish a bot, do I have to turn it into a .exe file?

wispy spade
slate swan
#

how do i do that

#

import discord
from discord.ext import commands

#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix='!', intents=intents)

@client.event
async def on_ready():
print('Bot is Ready.')

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

client.run('token')

burnt harbor
#

Exactly. Just do what the error tells you to. Having said that, I don't believe you need intents to access channel.purge. All that's required is read_message_history and manage_messages

wispy spade
wispy spade
slate swan
#

hm when i type !clear it gets errors

drifting arrow
drifting arrow
#

Neato

wispy spade
slate swan
#

FIXED IT YAY

drifting arrow
#

woo

wispy spade
slate swan
#

thank you for the help

drifting arrow
#

Even tho I didn't do anything, I will happily take credit

#

You're welcome @slate swan

slate swan
#

XD

wispy spade
burnt harbor
#

You will need more than just one .py file.

drifting arrow
burnt harbor
#

I don't know I've never run a bot as an executable

drifting arrow
#

So I'd upload the .py alongside everything I 'imported'? ๐Ÿค”

burnt harbor
#

yes

short axle
slate swan
burnt harbor
#

Show errors/code example/ questions in correct english?

drifting arrow
slate swan
#

most py2exe "compilers" will basically package a python interpreter and your code together

#

so the main benfit is just for distributing the code

drifting arrow
#

They'd still need to do the whole pip install <package>?

slate swan
#

oh wait

#

nope

slate swan
drifting arrow
#

Upload the bot to a VPS so the bot is always online

#

and maybe share the bots invite code

slate swan
#

I would personally just give people the .py file and tell them to pip install the packages

drifting arrow
#

And what about my own personal bots?

drifting arrow
maiden fable
slate swan
drifting arrow
#

@slate swan i found a vps. that's not my issue. My issue is. do I just upload the 1 script to the server? or do I have to grab all the packages as well?

slate swan
#

also, what vps if you don't mind me asking

drifting arrow
slate swan
#

let me check for packages

drifting arrow
#

Oh they require me to have ubunto or linux

brisk fiber
#

fwiw iโ€™m running a small bot on a raspberry pi and itโ€™s working well so thatโ€™s an option too (@ anyone else thinking about how to host their bots)

slate swan
#

oh it's actually pip install on the vps

#

not a requirements.txt so ignore all of that stuff

drifting arrow
slate swan
#

eg a package in the standard library is the random module

neat birch
#

Anyone Know How To Make A Bot Command Like If We Do - .delete [channel name] ( not channel mention) it deletes every channel in the server with that name

slate swan
#

can you have 2 channels with the same name?

maiden fable
#

No

drifting arrow
slate swan
#

i guess use the in keyword

#

i'll start it off for you

#
@client.command
async def delete(ctx, *, naming_convention):
  for channel in ctx.guild.text_channels:
    if naming_convention in channel:
      print(channel)
drifting arrow
slate swan
#

good idea

@neat birch

crimson cliff
#
import os
import discord
from discord.ext import commands, tasks
from itertools import cycle
import youtube_dl
import random
from keep_alive import keep_alive

@client.command()
async def play(ctx, url : str):
    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
    except PermissionError:
        await ctx.send("Wait for the current playing music to end or use the 'stop' command")
        return
#

Hi Guys
Why my play command is not working

drifting arrow
#

if song_there:
os.remove("song.mp3")

why you removing it?

neat birch
vagrant brook
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
crimson cliff
drifting arrow
#

TL;DR - voice bots no no.

crimson cliff
#

Can anyone reply

zenith flicker
#

is there a way to keep my bot online if i turn off my computer

visual island
#

if you still wish to run it in your computer, no

crimson cliff
#
@client.command()
async def play(ctx, url : str):
    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
    except PermissionError:
        await ctx.send("Wait for the current playing music to end or use the 'stop' command")
        return

    voiceChannel = discord.utils.get(ctx.guild.voice_channels, name='General')
    await voiceChannel.connect()
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            os.rename(file, "song.mp3")
    voice.play(discord.FFmpegPCMAudio("song.mp3"))
#

Can anyone reply ?

#

anyone??????????????????????????????

pliant gulch
#

You've been told already that YTDL is ToS breaking thus we will not help due to rule 5

neat birch
crimson cliff
drifting arrow
# crimson cliff

Also you could try googling 'discordpy connect to voice channel' and follow the multitude of guides or copy code or whatever.

drifting arrow
neat birch
#

oh

drifting arrow
#

To completely disregard any safety and what not, in the loop you'd grab the channel id and delete it right then and there

drifting arrow
#

no. but you'd have all the channels that match your given criteria

#

from there you can add in things like.. delete.

#

rename. or even simply send a message to that channel.

neat birch
#

oh

drifting arrow
#

alter the permissions. whatever you want! \o/

neat birch
#

ok

#

thank you

supple thorn
drifting arrow
#
@client.command
async def delete(ctx, *, naming_convention):
  for channel in ctx.guild.text_channels:
    if naming_convention in channel:
      print(channel) #channel is the channel that matches your criteria. so maybe do delete channel or something idk. up to you. just make sure it's here.
crimson cliff
supple thorn
drifting arrow
#

I never tested it so im not worried lol

maiden fable
#

If I input hey there but the channel name is hey-there. Discord replaces spaces with hyphens, forgot?

drifting arrow
#

then obviously you'd replace " " with "-"

crimson cliff
maiden fable
#

Yeaa

drifting arrow
pliant gulch
#

It doesn't break discord ToS

#

It breaks youtubes

#

And it also breaks copyright laws

supple thorn
#

Yeah

drifting arrow
#

Coz youtube says no.

pliant gulch
#

As some might know a big music bot was recently sent a C&D

covert igloo
supple thorn
#

07 groovy

covert igloo
#

Rythm still kickin it LOL

slate swan
unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
heavy radish
#

Hello

#

I would like some help!!

drifting arrow
neat birch
neat birch
drifting arrow
#

oh yeah. me too. hahaha just code. yep.

heavy radish
#
import discord
import os
from keep_alive import keep_alive

client = discord.Client(activity=discord.Activity(name="CEO's actions", type=discord.ActivityType.watching))

@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('Congratulations to'):
    await message.channel.send(f'`RPG Miniboss {message.content.split("Congratulations to ")[1]}`')

@client.command()
async def ping(ctx):
    await ctx.reply(f"\U0001f3d3 Pong! **{round(client.latency * 1000)}ms**", mention_author=False)


keep_alive()
client.run(os.getenv('TOKEN'))
heavy radish
#

The error is at client.command

trim barn
#
        candidate_votes = [int(vote_db.count_documents({"vote": str(candidate)})) for candidate in candidates.values()]
        total_votes = int(vote_db.count_documents({}))
        total_yesno = int(recall_yes_votes + recall_no_votes)

        x = np.array([candidate_votes])
        election_candidates = [str(x) for x in candidates.values()]
        candidate_colors = ["red", "blue", "yellow", "green", "purple"]
#

raise ValueError("x must be 1D") ValueError: x must be 1D

#

wait wrong one oops

neat birch
heavy radish
#

This

neat birch
#

Ig U Need a ':'

heavy radish
#

Line 20 is client.command

neat birch
#

After The ()

heavy radish
#

just : right?

#

lets try

neat birch
#
client.command():
#

ig so

heavy radish
#

syntax error

#

lol

neat birch
#

Hmm

drifting arrow
neat birch
#

Lol

lone aurora
#
class admin(commands.Cog):

    def __init__(self, client):
        self.client = client
    
    @commands.command()
    async def announce(self, ctx, *, message):
        if (ctx.author.guild_permissions.administrator):
            embed = discord.Embed(
            title = '',
            description = '',
            colour = ctx.author.colour  
            )
            embed.set_footer(text='By oSeatch#6969')
            embed.set_author(name=ctx.message.author)
            embed.add_field(name='News', value=message , inline=False)
            await ctx.send(embed=embed)
            await ctx.message.delete()
            return
        else:
            await ctx.send("__**This Command Requires a Higher Rank.**__")


def setup(client):
    client.add_cog(admin(client))``` Uhh what am i doing wrong?
pliant gulch
# heavy radish

Your getting the error because discord.Client does not have any commands extension. You want to use commands.Bot instead

neat birch
lone aurora
#

The command executes without any error but it says the command itself doesnt exist

supple thorn
#

@heavy radish

heavy radish
#

yes

pliant gulch
#

commands.Bot inherits discord.Client and adds the commands extension

supple thorn
#

Its commands.Bot

#

Not discord.Client

heavy radish
#

ok

#

i'll try

supple thorn
#

If you are gonna use commands

pliant gulch
#

Keep in mind you need to pass command_prefix to the constructor of commands.Bot

heavy radish
#

so

@commands.Bot ```
pliant gulch
#

no

heavy radish
#

oh

supple thorn
#

Also ```py
from discord.ext import commands

drifting arrow
#

Not now jerry

supple thorn
drifting arrow
neat birch
#

that's a long code KEKW

supple thorn
#

Replace it with commands.Bot

heavy radish
supple thorn
#

Nice

heavy radish
#

ok

supple thorn
#

After that it should work

drifting arrow
#

<@&831776746206265384>

heavy radish
#

then this wont work ```
activity=discord.Activity(name="CEO's actions", type=discord.ActivityType.watching)

supple thorn
#

Well

visual yarrow
#

Hello, what's the issue?

supple thorn
#

@heavy radish add command_prefix

heavy radish
#

Can u show me it in the code?

drifting arrow
#

Hey @visual yarrow, there was a user @slate swan sending images and not contributing to the topic of the channel.

heavy radish
#

I'm so lost

supple thorn
heavy radish
#

I can create a help channel

supple thorn
visual yarrow
#

@slate swan Keep on-topic in these channels please.

supple thorn
#

You posted Mr.Peanut

drifting arrow
#

I'll be recording your actions from now on @slate swan. Please stop this tom-foolery

hoary gust
#

Guys any async driver for mariadb?

visual yarrow
#

We do have message logs. There's no point arguing over this.

supple thorn
#

Gnome went full british

drifting arrow
lone aurora
#
class admin(commands.Cog):

    def __init__(self, client):
        self.client = client
    
    @commands.command()
    async def announce(self, ctx, *, message):
        if (ctx.author.guild_permissions.administrator):
            embed = discord.Embed(
            title = '',
            description = '',
            colour = ctx.author.colour  
            )
            embed.set_footer(text='By oSeatch#6969')
            embed.set_author(name=ctx.message.author)
            embed.add_field(name='News', value=message , inline=False)
            await ctx.send(embed=embed)
            await ctx.message.delete()
            return
        else:
            await ctx.send("__**This Command Requires a Higher Rank.**__")


def setup(client):
    client.add_cog(admin(client))``` Anyone? ._.
lone aurora
#

the bot works fine, the other commands work too but when i do this one it just says that the command doesn't exist

#

Uhuh?

#

no crap

drifting arrow
lone aurora
#
def setup(client):
    client.add_cog(admin(client))``` it should auto load
drifting arrow
#
@bot.command()
@commands.is_owner()
async def load(ctx, extension):
    bot.load_extension(f'cogs.{extension}')

@bot.command()
@commands.is_owner()
async def unload(ctx, extension):
    bot.unload_extension(f'cogs.{extension}')


for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')

@lone aurora you can use any of this to load the cog. either via command or just auto

hot cobalt
#

@slate swan You can claim a help channel if you want, this channel is for discord.py, which the code you posted isn't related to

lone aurora
#

but the rest of my cogs enable on bot start, why doesnt this one

hot cobalt
#

@slate swan Please don't try to ping everyone

drifting arrow
#

So wherever your discordbot.py script is, add a new folder called "cogs" and it put your "cogs" in that folder

hot cobalt
#

@slate swan Did you not see what I said?

crimson cliff
#

:/
MY Bot doesn't work on music command
I can't even send code bcoz u guys said YTDL is breaking (Given in rule 5 )
๐Ÿ˜ฆ

hot cobalt
#

This channel is in relation to discord bots, your code is not, so please claim a help channel (see #โ“๏ฝœhow-to-get-help) if you want to discuss your code

drifting arrow
#

@lone aurora like so:

lone aurora
drifting arrow
#

well there you go

#

we figured it out and all it took was me doing something else ;D

maiden fable
#

Breh

lone aurora
drifting arrow
#

Hey @slate swan, I dont normally block people, but you're getting up there fast. please stop this. we can be friends not me ignoring you

hot cobalt
#

alright

#

!pban 650902544176119809 That's about enough, we're not going to tolerate trolls

crimson cliff
#

Bro Try to respect or else get ban

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied purge ban to @peak mango permanently.

maiden fable
#

Thanks (:

drifting arrow
#

Ty @hot cobalt

boreal ravine
hot cobalt
#

Because it's viewed as spam

boreal ravine
#

spam?

#

isnt it a single line tho

hot cobalt
#

Spam doesn't have to mean multiple messages, it's just unwanted/undesired messages

drifting arrow
#

@boreal ravine A vast majority of servers disable the ability to use @ everyone because of how many it tags at once.

sweet merlin
#

how do i make multi processing in discord.py?
I want to make a bot command that download some links into my laptop, i want to make it multi process so i dont wait until the first links downloaded

i tried using multiprocess lib but it didnt work

#sorry if my english was bad :(

drifting arrow
# boreal ravine im not dumb.

as a result, in discords where channels are separated by topic, such as this one, if you could use @ everyone you'd bring people in who quite frankly, don't care about discord bots at all. Which would be annoying.

boreal ravine
#

okay

drifting arrow
#

TL;DR think of it as a loud annoying kid running into the supermarket and screaming shit. Annoying as fuck.

untold token
#

You can create commands/ tasks that will install whatever file you want

cyan bay
#

hey, so im trying to make a bot like dank memer, where if you type "pls meme" a meme pops up

clever wind
#
@lobby1.command()
async def start(ctx):
    queue1 = client.get_channel(883963916915453962)
    queue1_members = queue1.members

    queue1_members_mention = []
    for member in queue1_members:
        queue1_members_mention.append(member.mention)

    random.shuffle(queue1_members_mention)

    global lobby1_team_a
    global lobby1_team_b
    lobby1_team_a = queue1_members[len(queue1_members) // 2:]
    lobby1_team_b = queue1_members[:len(queue1_members) // 2]

    global lobby1_team_a_mention
    global lobby1_team_b_mention
    lobby1_team_a_mention = []
    for member in lobby1_team_a:
        lobby1_team_a_mention.append(member.mention)
    lobby1_team_b_mention = []
    for member in lobby1_team_b:
        lobby1_team_b_mention.append(member.mention)

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

@lobby1.command()
async def result(ctx, *, result):
    db = sqlite3.connect('my_database.db')
    cursor = db.cursor()

    result = str(result)

    global lobby1_team_a
    global lobby1_team_b

    lobby1_team_a_id = []
    for member in lobby1_team_a:
        lobby1_team_a_id.append(member.id)
    lobby1_team_b_id = []
    for member in lobby1_team_b:
        lobby1_team_b_id.append(member.id)

error: name 'lobby1_team_a' is not defined --> why is this? i declared global on it

untold token
#

As you are not processing it

cyan bay
cyan bay
#

i have created an array with the urls of the memes, but i want those memes to yknow, not the be same

#

what i mean is, i want those memes to be different every day

drifting arrow
#

@cyan bay how are you getting these memes to begin with?

untold token
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").

Example...
cyan bay
cyan bay
#

so i find a meme in reddit, i copy the url of the picture, not the post, then i put it in the array

drifting arrow
untold token
#

Or asyncpraw for it

cyan bay
drifting arrow
cyan bay
untold token
#

Yes

untold token
#

You can use the reddit API itself

cyan bay
#

how do u use the reddit api?

drifting arrow
#

A vast majority have the same setup. But then it changes based on how the api is setup. In discord, it's weird with guilds and channels. Reddit has weird references. google has its own shit to deal with. etc etc

untold token
#

It's an API wrapper for reddit API

cyan bay
#

ok

drifting arrow
#

If you dont wanna learn how to actually use an API and just want to use a library, there's a good library called PRAW

untold token
#

Asyncpraw btw

#

Praw is blocking

drifting arrow
#

Or if you wanna be weird and be like me, figure out how to use an api and make your own reddit api connections /shrug

untold token
#

Make sure it is asynchronous

cyan bay
#

im kinda new to asyncpraw, so whats the code to refresh the memes?

heavy radish
untold token
#

Error?

heavy radish
#

BTW, Which one are u talking about??

#

no errors. the bot does reply

untold token
#

Okay good then

heavy radish
#

wait, doesnt

#

lol

drifting arrow
#

@cyan bay You'll need to figure that part out yourself.
But if I was going to do it based on reddit posts and every say 12 hours, I'd get a background task which waits every 6/12/18/24 hours or whatever. Which it then at those intervals checks the reddit memes page you specify via your reddit api and updates a list. Upon which you simply update your list and import random and randomize the memes.

heavy radish
#

I have 2 bot.event which one do u want me to change??

untold token
#

Listeners are better than events,
They are external listeners that will listen to your event asynchronously and respond accordingly, and won't block other listeners and commands

heavy radish
#

first or second??

untold token
#

You can change the on_ready one too

heavy radish
#

ahh it doesnt work

untold token
#

Wdym doesn't work

untold token
#

If you don't want same random memes

#

I suggest you to look at caching

heavy radish
#

Its not for memes

#

Should I dm support server??

drifting arrow
#

Not you @heavy radish

heavy radish
#

ahh

untold token
#

Lol

drifting arrow
#

We're helping some other kiddo get his meme on

heavy radish
drifting arrow
#

Which i totes approve.

untold token
#

You can cache memes and check if repeated memes are sent or not

untold token
heavy radish
#

OK

drifting arrow
#

I mean. it's reddit. Ofc they are being sent over and over and over again

untold token
#

Does it error? @heavy radish

drifting arrow
#

!background

#

!d background

unkempt canyonBOT
#

Qt Style Sheets support various properties, pseudo-states, and subcontrols that make it possible to customize the look of widgets.

drifting arrow
#

nope not what i wanted

#

how do I make the bot give me info on background tasks ;-;

#

!d background tasks

unkempt canyonBOT
#

Qt Style Sheets support various properties, pseudo-states, and subcontrols that make it possible to customize the look of widgets.

drifting arrow
#

yeah na fuck u bot.

valid perch
#

Define give me info @drifting arrow

clever wind
#
#Check OVR
@client.command(pass_context=True)
async def check_stats(ctx, *, member: discord.Member):

    user_ign = get_user_ign(member.id)
    user_ovr = get_user_ovr(member.id)
    user_elo = get_user_elo(member.id)
    
    print(str(user_ovr))
    
    if user_ovr in range(93, 100):
        colour = discord.Colour(0xe91e63)
    elif user_ovr in range(87, 93):
        colour = discord.Colour(0x1abc9c)
    elif user_ovr in range(81, 87):
        colour = discord.Colour(0xf1c40f)
    elif user_ovr in range(75, 81):
        colour = discord.Colour(0x95a5a6)
    elif user_ovr in range(0, 75):
        colour = discord.Colour(0xc27c0e)
    

    embed = discord.Embed(title=f"{user_ign}'S STATS", colour=colour)

    embed.set_image(url=member.avatar_url)
    embed.set_footer(text="Hive 4v4s",
                     icon_url="https://cdn.discordapp.com/embed/avatars/0.png")

    embed.add_field(name="OVR", value=f'{user_ovr}', inline=True)
    embed.add_field(name="ELO", value=f'{user_elo}', inline=True)
    await ctx.send(embed=embed)

error: local variable 'colour' referenced before assignment

help.. ping on reply

slate swan
slate swan
#

^

clever wind
#

thats odd, the user_ovr is 95

#

it even prints 95

#

could it be that user_ovr isn't an int?

maiden fable
#

Yea

#

That's a possibility

clever wind
#

ah that was it

#

it works ๐Ÿ˜„

stark bobcat
#

!charinfo โœ…

unkempt canyonBOT
lone aurora
#

await client.change_presence(activity=discord.Game(name='Do &cmds'))
AttributeError: module 'discord.client' has no attribute 'change_presence'

#

Anyone?

drifting arrow
#

Just finished moving all my commands into their own lil' cogs. accidentally overindented everything ;-;

#

but is work now ๐Ÿ˜„

unkempt canyonBOT
#

Hey @fallow anchor!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

drifting arrow
lone aurora
#

File "C:\Users\HP\Desktop\dc bot\cogs\events.py", line 16, in on_ready
await bot.change_presence(status=discord.Status.idle, activity=discord.Game('&cmds'))
AttributeError: module 'discord.ext.commands.bot' has no attribute 'change_presence'

lone aurora
lone aurora
slate phoenix
#

you have to use self

boreal ravine
#

self.client

slate phoenix
#

self.bot.change_presence

lone aurora
#

i c thanks

drifting arrow
#

oh

#

i didnt know it was in a cog xD

#

How do I give all these commands a description whenever I type $help?

boreal ravine
lone aurora
boreal ravine
#

not rlly

#

default help command is ok and customizable

lone aurora
#
client = commands.Bot(command_prefix = '&', intents=intents, case_insensitive= True, help_command=None)``` im doing this and then i created an embed for the help cmd ._.
boreal ravine
#

yes

#

there are 3 kwargs for help commands i think

limber rivet
#
  • Serving Flask app '' (lazy loading)
  • Environment: production
    Traceback (most recent call last):
    File "main.py", line 28, in <module>
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
    client.run(os.getenv('TOKEN'))
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
  • Serving Flask app '' (lazy loading)
  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
    Traceback (most recent call last):
    File "main.py", line 28, in <module>
    client.run(os.getenv('TOKEN'))
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
  • Serving Flask app '' (lazy loading)
  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
    Traceback (most recent call last):
    File "main.py", line 28, in <module>
    client.run(os.getenv('TOKEN'))
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
    File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
    Traceback (most recent call last):
    File "main.py", line 3, in <module>
    from keep_alive import keep_alive
    File "/home/runner/ASFR-BOT/keep_alive.py", line 18
    ot make any noises or troll using your mic. Trolling would include anything from playing music with your microphone to screaming at the top of your lungs for now apparent reason. Voice changers like voice mod are prohibited within ASFR. Rule 16: โžฅ You may not ping any role.โ€ขThis rule regards to mass pinging individuals that have a specific ')
    ^
    SyntaxError: 'await' outside async function
slate phoenix
#

thats a huge error message

limber rivet
#

the code is 4k+ words

boreal ravine
#

wym

#

show the code where the error happened

limber rivet
#

k

#

the whole is thing red

boreal ravine
#

show the code

#

where the error happened

limber rivet
#

k sec

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

boreal ravine
#

wut

slate swan
#

Don't paste it here if it's big

#

It will just flood the chat for nothing

drifting arrow
#

Neato ๐Ÿ˜„

slate swan
#

You miss close bracket

boreal ravine
#

wut

slate swan
#

If you want change line use \n

boreal ravine
#

wut

slate swan
#

Yep

slate phoenix
#

post the entire code for the command

slate swan
#

Yea maybe want write rules i guess

slate phoenix
#

but your error shows you used a coroutine outside of an async func

limber rivet
slate swan
#

Use \n for new line

boreal ravine
#

what

slate swan
#

As you already got told

boreal ravine
#

no i asked for the code

#

not the rules??

limber rivet
#

wait

slate swan
#

And I'd guess @fallow anchor is your alt

#

Or use \ for bot can read next line

limber rivet
slate swan
#

Use \n

#

Yea the better way

#

and dont use events for create commands

#

^

boreal ravine
#

or just type out the rules yk

slate phoenix
#

a rules channel usually works yeah

limber rivet
#

alr, ty

stark bobcat
#

why does this error come

crude crater
crude crater
limber rivet
crude crater
#

Google the error and I guarantee itโ€™ll tell you lol

crude crater
limber rivet
#

yw

maiden fable
maiden fable
lament mesa
#

That might be a warning and not an error

maiden fable
#

Yea

white perch
#

What's wrong with my code?

stark bobcat
white perch
drifting arrow
stark bobcat
# maiden fable Can u paste the code here?
@bot.event
async def on_message(message: discord.Message):
  if message.guild is None and not message.author.bot:
    print(message.content)  
    print(message.author)

    embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
  
    a=await message.author.send(embed=embed)
    await a.add_reaction('\u2705')
    await a.add_reaction('\U0001f6ab')

    def check(reaction, user):
      return user == msg.author and str(reaction.emoji) in ["\u2705", "\U0001f6ab"]```
drifting arrow
white perch
#

Its not anything related to youtube

drifting arrow
#

TL;DR - music bots not allowed. naughty. bad.

white perch
#

WHAT??

#

How is that a music bot code

#

Its just a tts thing

drifting arrow
#

Audio bots*

white perch
#

text to speech command

slate swan
#

Audio bots are allowed

white perch
#

Nto even using youtube at all

drifting arrow
#

They are?

slate swan
#

Don't mislead people

#

It has nothing to do with YouTube

drifting arrow
#

But earlier people were saying they werent ๐Ÿ˜ 

lament mesa
#

this is not a music bot

white perch
#

If you have your own music saved in somewhere and doesn't include Youtube then you are ALLOWED to use it on discord bots

drifting arrow
#

this is confusing. im going to take a shower.