#discord-bots

1 messages · Page 929 of 1

quaint epoch
#

wow i should've done this long ago

static beacon
#

and not filter butt

boreal ravine
#

just reminding you that it's optional 😡

quaint epoch
#

.bm

keen lynx
quaint epoch
#

thank you

static beacon
quaint epoch
#

i tried to find a package for this but only found a couple that did not support leetspeek

slate swan
slate swan
manic wing
#

examples of what?

slate swan
manic wing
#

need me to teach you okimii?

slate swan
boreal ravine
manic wing
#

unfortunately my cellular device does not have a scroll wheel

final iron
slate swan
#

and kayle knows hes just too lazy/hes on mobile

final iron
boreal ravine
#

lazyreally

grim oar
#

Erotic

boreal ravine
#

Wrong channel?

#

not a valid url

zinc otter
#

I suppose that the webhook is taking input from a text channel where someone said "lol"?

#

Oh ok

#

You did elses with exceptions

#

You should try doing

#

try:
# Code
except ValueError:
# Code for ValueError
except Exception:
# Code for any other error

#

That should work

cold sonnet
#

that's interesting

#

controlling the discord bot from a panel seems like such a creative idea

zinc otter
#

ye that's pretty cool

#

thx

#

Nothing pops out?

#

You replaced the comments with the code to execute right?

#

It doesn't pop out no message box?

slate swan
#

how to set embed color in hex format?

zinc otter
#

that's strange

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

zinc otter
#

Try doing a message box outside all the exceptions to see if code is running correctly

#

Like a debugging message

#

I don't think so

#

try removing the Exception

#

At the second except

#

And btw try putting the except with no Exception at the end of the exceptions

#

I don't know if I'm explaining well

final iron
#

How about no

#

Using a bare except is a terrible idea

zinc otter
slim ibex
#

Do NOT do this

slate swan
slim ibex
#

and you generally don’t want to catch the system exiting exceptions

zinc otter
hallow tangle
#

how to obtain interaction endpoint url?

slim ibex
#

please except the exact error

#

if you want to handle multiple errors, do multiple except blocks or

#

except (ExceptionsHere)

slate swan
#

are the exception groups out?

slim ibex
hallow tangle
unkempt canyonBOT
#
**PEP 643 - Metadata for Package Source Distributions**
Status

Final

Created

24-Oct-2020

Type

Standards Track

slim ibex
#

Wrong one

slate swan
#

i forgot the num of the pep

slim ibex
#

!pep 654

unkempt canyonBOT
#
**PEP 654 - Exception Groups and except***
Status

Accepted

Created

22-Feb-2021

Type

Standards Track

slim ibex
#

I’m guessing HTTPException

hallow tangle
#

no one replied, sad

south jetty
#

Can someone help me,
I am trying to code my ticket bot to get the list of users that had sent a message in the channel which will need a db
But I am not quite sure on how to do it

manic wing
#

sounds like a cool idea, whats the issue?

south jetty
#

I don't have an idea on how its done.
I have browsed through but have no clue

#

I thought someone here has experience on this and could explain

manic wing
#

whats your experience with discord bots?

#

this may prove to be harder than necessary without experience

slate swan
#

cant you just use TextChannel history?

south jetty
slate swan
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

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

Examples

Usage...
slate swan
#

Let me find it

#

Hm seems AsyncIterator has been removed

#

I think you can just do

messages = [m async for m in channel.history(limit=...)]

To get a flattened list of messages

manic wing
#

you can flatten it just fine

south jetty
#

Then to get the users that have sent a message in the channel

lost lichen
#

how can i send a message to a specific channel ID?

#

disnake

slate swan
#

!d discord.Client.get_channel

manic wing
unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
slate swan
#

Just use channel.send() after that.

#

If you don't have it cached, then you have to some unconventional stuff with HTTPClient, which is against the design language of dpy.

lost lichen
#

so ```py
channel = self.bot.get_channel(id)
channel.send(embed=embed)

#

im running it in a cog

slate swan
#

Try it

manic wing
slate swan
#

Might wanna check if channel is None too, which is the case if it's not cached.

lost lichen
#

how does the cache work

#

as in why would the channel not be cached

#

under what circumstance does it become cached

manic wing
#

you dont want to get in to that

slate swan
pliant gulch
manic wing
#

all the functions you would want to do would be available to you through the bot

unkempt canyonBOT
#

discord/http.py line 590

def send_message(```
lost lichen
#

nice, thanks! worked! i was doing a wrong attribute

manic wing
slate swan
#

It's not that complicated yk..

#

It's just a dict

#

*NamedTuple

pliant gulch
#

Kind of weird for it to be a NamedTuple imo

slate swan
#

How?

unkempt canyonBOT
#

discord/abc.py line 1403

with handle_message_parameters(```
manic wing
pliant gulch
# slate swan How?

Because you could just make a "master" dict, then add all your keys, etc

manic wing
#

a singular api call probably isnt worth the chaos you would need to pass that shit

slate swan
#

"All that shit"?

#

You literally only actually need params.payload

#

And it can be a {'content': ...} dict

slate swan
#

With the __exit__() method of the named tuple.

manic wing
#

different story for files

slate swan
#

How?

#

Just construct the named tuple with files being a list of discord.File objects

pliant gulch
#

Not that it matters much although

slate swan
#

But like I said, still unconventional. Not a major PITA tho.

manic wing
#

you're right, it isnt all that hard to pass your own payload, but its unconventional and probably wouldnt be worth the hassle to just make a singular api call

#

considering more than most of the people you would recommend the 'unconventional stuff with HTTPClient' wouldnt understand the half of what is going on

slate swan
#

No actually, I don't know why I brought up the http client. I don't generally recommend it at all.

pliant gulch
#

discord.py's RESTful interface could've been a lot better

#

One of pythons selling points is hackablity imo

#

It would've been niced to have the option to use the HTTPClient in a sane way

slate swan
#

Well, it's internal so I guess we all have to just sit back and cry

pliant gulch
#

Don't even get me started on the O(n) message cache

#

😔

slate swan
#

At least me, I would have loved a more stateless client.

slate swan
#

I've never actually tried to learn about it

#

I might now

pliant gulch
#

There for if we have 10 oranges, it takes me longer time to count them, compared to 5 oranges

slate swan
#

Oh yeah definitely, ConnectionState._get_message() is atrocious.

pliant gulch
#

discord.py could've had an O(1) message cache, meaning constant time. Therefor if I had 10 oranges, it would take same time to count them as the 5 oranges from earlier

#

dicts are ordered, they could've just impl __setitem__ to pop

slate swan
#
 def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
     return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None

Danny wtf

pliant gulch
#

It's cause of the deque

#

Should've used dict for that juicy hash map

slate swan
#

At least he reverses it

pliant gulch
#

My own impl already has it 😼

rocky trench
#

how do I check if a channel is a textchannel?

final iron
#

Maybe isinstance

#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
final iron
#

!e

str_var = "my string"
if isinstance(str_var, str):
    print("a")
unkempt canyonBOT
#

@final iron :white_check_mark: Your eval job has completed with return code 0.

a
final iron
#

@rocky trench

rocky trench
#

Thx

velvet tinsel
#

Thx

dull terrace
#

You ever work on something dumb for way too long

#

i think i finally got my dash generator to actually get equal length strings for discord

#

test - - - - - - - - - - - - - - - test
longer test - - - - - - - - - - test
even longer test - - - - - - -test
$sym0Ls[]&stuff - - - - - -test

final iron
#

Willing to share the code?

dull terrace
#
from PIL import Image, ImageFont, ImageDraw
discord_font = ImageFont.truetype("WhitneyBook.ttf", 1600, encoding="unic")
def dash_gen(string):
    length = discord_font.getsize(string)[0]
    while length < 16820:
        if length < 16820:
            string += " "
            length += 362
        if length < 16709:
            string += "-"
            length += 582
    return string
#

then i got a big ass dictionary with all the character sizes

final iron
#

Interesting

dull sorrel
#

await message.channel.send("LOL",
What argument should I add to mention a specific user?

final iron
#

You wouldn't use an argument

dull terrace
#

<@USER_ID>

dull sorrel
#

How about replying?

final iron
#

!d discord.Member.mention

unkempt canyonBOT
dull terrace
#

i think there may be an ! in there somewhere

final iron
unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
final iron
#

It's a different method

dull sorrel
#

I am not sure I understand. How do I add the author id?

#

Also could you complete the code, please?

final iron
unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.id "discord.User.id")
dull sorrel
final iron
#

Like have the command take an id param?

final iron
#

That's not what this server is for

dull sorrel
#

How do I do that?

final iron
#

Like in a command?

dull sorrel
#

I want to know how to do both.

final iron
slate swan
#

If you typehint the argument as discord.User, it supports both id and user mention

dull sorrel
#

@client.event
async def on_message(message):

if message.author == client.user:

    return


if message.content.startswith("LOL") and message.author.id == :

    await message.channel.send("LOL",)
#

This is my code.

slate swan
#

That's not a command, it's an event.

dull sorrel
slate swan
river swift
#

How do I put the messages of a bot in an embed message, could someone help me?

slate swan
#

Use the discord.Embed class to make an embed and use the embed kwarg in . send () while sending it

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, 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.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
river swift
#

would this be ok?

dull terrace
river swift
dull terrace
#

the tiny bit the length is off is making me mad

final iron
#

Then name will be the item

dull terrace
#

because mobile is dumb and puts each field on a new line

final iron
#

Doesn't seem like a big deal to me

dull terrace
final iron
#

Nah like create a different field for each item

dull terrace
#

looks awful and takes up too much space

slate swan
#

how can i make it so if the user answers too fast it says something like, dont copy and paste that!

dull terrace
#

i've tried literally every option, dashes is for some reason the best

river swift
#

Would this be alright, handsome guys?

dull terrace
#

well since you called me handsome?

river swift
dull terrace
#

would it be alright for what

river swift
dull terrace
#

my definition of well programmed is whether it runs

halcyon sparrow
#

Is this a user error? errors.ConverterFailure(*args: t.Any, opt: commands.base.OptionLike, raw: str)

halcyon sparrow
#

If a converter fails it's the users fault? I feel like it is?

halcyon sparrow
#

Are you writing this in a single file or separate from the main thing

river swift
#

a single file

halcyon sparrow
#

I'm using hikari. I don't know the library you're using sorry. A good thing to do is go back and look at your other commands that work

halcyon sparrow
#

Do you have other commands that work?

dull terrace
slate swan
river swift
halcyon sparrow
#

Yeah, I thought so. Its a user error. Thanks. I don't mind the pings.

slate swan
#

anyone know how to delete all channels in a discord server with a command

#

it can be, but is not limited to a user error, any factor causing the argument to not get converted to that required class can cause that error

unkempt canyonBOT
#

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

slate swan
slate swan
# final iron !rule 5

i need help cuz a server got raided and i'm trying to delete all the channels tryin to do the oppsoite atm

#

and then check that timedelta on your own convinience

slate swan
river swift
#

how to fix this guys :,,,,,v

slate swan
manic wing
#

or help_command=None

river swift
#

BURGGHHHH

river swift
slate swan
# river swift
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="YOUR PREFIX")

bot.remove_command('help')```
heavy folio
#

and dont make your own help command if you plan to.

silent ermine
heavy folio
#

what

silent ermine
#

so client.remove_command('help')

#

blobshrug its simpler

slate swan
silent ermine
slate swan
silent ermine
slate swan
#

!d discord.ext.commands.Bot.help_command

unkempt canyonBOT
silent ermine
#

i prefer to use the old methods so dont mind me

slate swan
silent ermine
silent ermine
silent ermine
slate swan
#

yes

silent ermine
#

how to color the whole codeblock red

heavy folio
#

yeah pov you added 69 commands and you gotta manually add it in your horrible help command

#

why tf did it not reply

silent ermine
#

be smart

#

that way you only have to add description in decorator

pliant gulch
#

if not description already covers description being ""

#

Same with it being None, your other part of the if statement is use-less 100%

silent ermine
pliant gulch
#

Computers don't mess this up 🤔

silent ermine
pliant gulch
#

And you could remove your ternary condition inside of the f-string

#

Using just or

#

This would give a speedup

silent ermine
final iron
#

Andy can you optimize my life 😔

silent ermine
#

anyone know json here

pliant gulch
final iron
#

😡

final iron
silent ermine
#

i have to implement it to a discord command

final iron
silent ermine
final iron
#

Full stop

silent ermine
heavy folio
#

though you could just use Context.clean_prefix to replace !

cloud dawn
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, 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.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
river swift
silent ermine
cloud dawn
manic wing
#

wtf is wrong with panda

silent ermine
#

if he doesnt know since people dont want to help me because using json is a bad idea but idc

dull terrace
cloud dawn
dull terrace
#

Fits on one screen now woo

buoyant igloo
#

I know something about json, I don’t know if I will be able to help

silent ermine
tawny swallow
#

Why the command is not working?

cloud dawn
tawny swallow
manic wing
#

i beg that you’re doing bot.run

tawny swallow
manic wing
#

you’re … not calling bot.run?

tawny swallow
manic wing
#

replace .event to .listen()

cloud dawn
slate swan
cloud dawn
manic wing
#

!e
x = 0
x = 1
print(x)

unkempt canyonBOT
#

@manic wing :white_check_mark: Your eval job has completed with return code 0.

1
slate swan
manic wing
#

as panda rightly said, if a variable is redefined nothing happens to the previous definition

slate swan
#

Welp tnx

tawny swallow
tawny swallow
cloud dawn
#

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

manic wing
cloud dawn
#

lol

slate swan
pliant gulch
#

Of course it does

#

not

cloud dawn
slate swan
tawny swallow
velvet tinsel
tawny swallow
slate swan
velvet tinsel
slate swan
#

Mr Caeden you gotta chill cuz that fixes everything as you said down_syndromesmile

tawny swallow
# cloud dawn Could you show some more code I don't think the problem is here.

bot = commands.Bot(command_prefix = '%')

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

@bot.listen()
async def test(ctx, arg):
await ctx.send(arg)

#*respond to messages
@bot.event
async def on_message(message):
msg = message.content
user = message.author
if user bOt.UsEr :
ReTuRn
If MsG 'test':
await message.channel.send('test worked')

bot.run(token)

manic wing
#

that emote name is questionable

manic wing
#

read exactly what i told you to do.

manic wing
#

you did exactly the wrong thing.

#

i don’t think i could’ve been more clear

slate swan
#

BoT.UsEr

cloud dawn
tawny swallow
manic wing
#

in the on_message, replace .event to .listen().

#

i didnt say .command() to .listen().

cloud dawn
silent ermine
leaden jasper
manic wing
tawny swallow
silent ermine
tawny swallow
silent ermine
manic wing
silent ermine
manic wing
#

there is a difference

tawny swallow
slate swan
#

The syntax is wrong

leaden jasper
tawny swallow
# manic wing what i said, works. what you did, didnt work.

bot = commands.Bot(command_prefix = '%')

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

@bot.command
async def test(ctx, arg):
await ctx.send(arg)

#*respond to messages
@bot.listen()
async def on_message(message):
msg = message.content
user = message.author
if user bOt.UsEr :
ReTuRn
If MsG 'test':
await message.channel.send('test worked')

tawny swallow
slate swan
#

Also please use this

tawny swallow
slate swan
#

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

tawny swallow
hushed galleon
#

dont forget @bot.command should end with parentheses ()

slate swan
#

bot = commands.Bot(command_prefix = '%')

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

@bot.command()
async def test(ctx, arg):
await ctx.send(arg)

#*respond to messages
@bot.listen()
async def on_message(message):
msg = message.content
user = message.author
if user == bot.user :
return
If message.content == ('test'):
await message.channel.send('test worked')

tawny swallow
#

I forgot to added back

#

I AM SORRYYY

#

Thank you all

#

@manic wing sorry again and thank you

cloud dawn
slate swan
#

Its not mine

tawny swallow
cloud dawn
tawny swallow
#

Sorry for making you get mad lol

manic wing
#

whos mad?

slate swan
tawny swallow
cloud dawn
#

Pretty funny way of saying it~

slate swan
tawny swallow
cloud dawn
hollow badger
#

You do not deserve to have your feelings hurt.

tawny swallow
slate swan
#
Ignoring exception in command suggest:
Traceback (most recent call last):
  File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 64, in suggest
    title = {ctx.author.username},
AttributeError: 'Member' object has no attribute 'username'

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

Traceback (most recent call last):
  File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'username'
#

can yall help me with this??

#

this is the code

slate swan
#

so just name?

cloud dawn
#

nickname is .nickname

cloud dawn
slate swan
#

i want it to be like seff<33#9999

cloud dawn
manic wing
manic wing
slate swan
manic wing
native wedge
#

how to do task loop in python?

#

like every hour send a message

manic wing
#
from discord.ext import tasks

@tasks.loop(hours=1)
async def send_message():
  ... # send message
send_message.start()```
slate swan
#

Microsoft Windows [Version 10.0.19044.1586]
(c) Microsoft Corporation. All rights reserved.

C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot>python main.py
Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 64, in suggest
title = message.author,
AttributeError: 'str' object has no attribute 'author'

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

Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'author' @cloud dawn

cloud dawn
manic wing
slate swan
cloud dawn
#

This got more confused than needed lol

slate swan
#

The f outsied

cloud dawn
manic wing
# slate swan wym

well a dictionary is useful because it can store a key and a value, if you dont need the value you may want to just use a list

silent ermine
silent ermine
cloud dawn
#

I'm off to bed 👋

manic wing
#

goodnight panda

slate swan
cunning garden
#

No les molesta que hable español?

manic wing
#

please try to speak english to the best of your ability

cunning garden
#

Ñ

cloud dawn
#

Te molestan que hables español.
||They do bother you speak spanish.||

manic wing
#

good morning panda

slate swan
#

Gn guys ima go

cloud dawn
cloud dawn
cunning garden
#

Ñ por si acaso

hollow badger
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

hollow badger
#

Please use English @cunning garden

cunning garden
#

Ok

slate swan
abstract kindle
#

how would I grab the content of a message that is code formatted

#

I'm trying to make it so the eval command runs even if you try to eval it in code format

#

Nevermind, I just had the bot strip the ` characters

torn sail
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
slate swan
#

like do you just put exactly what’s there

torn sail
#

Wdym

#

embed.set_footer(name=ctx.author, icon_url=ctx.author.avatar_url if ur in v2 then avatar_url would be avatar.url

slate swan
#

alright where do i put it

#

under title? or above @torn sail ^

torn sail
#

After u define embed

slate swan
#

so under embed = discord.embed?

torn sail
#

Yea

slate swan
#

okay one sec

silent ermine
torn sail
#

No it should be outside the parenthesis. Just create a line above get_channel and put it there

silent ermine
hushed galleon
#

embed methods like set_footer can be tacked onto the end of the embed definition

torn sail
#

Or that but in my opinion it looks odd

silent ermine
#

outside of paranthesis, so put it above channel

slate swan
#

Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 70, in suggest
embed.set_footer(name=ctx.author, icon_url=ctx.author.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'

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

Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'

hushed galleon
silent ermine
#

replace avatar_url with avatar.url

#

only that piece ^

slate swan
#

Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 70, in suggest
embed.set_footer(name=ctx.author, icon_url=ctx.author.avatar.url)
TypeError: set_footer() got an unexpected keyword argument 'name'

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

Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_footer() got an unexpected keyword argument 'name'

hushed galleon
#

eh depends how you format it

#

for footer the kwarg is text= rather than name=

torn sail
#

Oh I meant embed.set_author @slate swan

#

Not set_footer

slate swan
#

alr

daring olive
silent ermine
#

how do I parse a string by the symbol %%

bleak karma
#

why is this showing an error?

steep estuary
#

;-;

bleak karma
#

wrong server oops

steep estuary
bleak karma
steep estuary
#

;-;

#

any error ?

#

show the terminal pls

slate swan
#

@torn sail

#

Ignoring exception in command suggest:
Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 185, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\youse\Downloads\Airline\DiscordBots\FlyAscent\Embed bot\main.py", line 70, in suggest
embed.embed.set_author(name=ctx.author, icon_url=ctx.author.avatar.url)
AttributeError: 'Embed' object has no attribute 'embed'

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

Traceback (most recent call last):
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 1182, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 904, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\youse\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 194, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Embed' object has no attribute 'embed'

torn sail
slate swan
slate swan
#

@torn sail @slate swan tyvm

#

TabError: inconsistent use of tabs and spaces in indentation

daring olive
#

since it's not discord bot specific

#

feel free to ping me after claiming one

alpine furnace
#

Yes

#

Refactoring is a good practice

#

Can learn a lot

#

Use a managed database provider

austere quartz
#

yo anyone knows wer to host discord bots

slate swan
#

What is auto complete

#

???

boreal ravine
#

yes

#

by making it

#

what database do you wanna use?

boreal ravine
#

do you know SQL?

slate swan
#

How can i make it so, when a user types Change, The discord channel changes it name to "Change"

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
cosmic agate
#

await bot.commit()
AttributeError: 'Bot' object has no attribute 'commit'

#

help

maiden fable
#

await bot.db.commit()

cosmic agate
#

oh ok

#

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 3 supplied

#
            await cursor.execute("UPDATE levels SET xp = ? WHERE USER = ?", (xp, author.id, guild.id,))
#

someone?

maiden fable
#

U have 2 vars buy supplying 3

sick birch
cosmic agate
#

hmm

inner epoch
#

Is it possible to setup webhooks using bot?

maiden fable
unkempt canyonBOT
#

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

Creates a webhook for this channel.

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

Changed in version 1.1: Added the `reason` keyword-only parameter.
inner epoch
cosmic agate
#

hey so

#

i have a leveling command

#

i try to to do !level

boreal ravine
cosmic agate
#

sqlite3.OperationalError: no such column: ctx.guild

#

should i change it to guild

#

or something else?

sick birch
#

Also are you using sqlite or aiosqlite?

cosmic agate
#

aio

sick birch
#

Your error says sqlite3 but you're awaiting your statements

cosmic agate
#

hmm

#

so i shouldnt await?\

sick birch
#

You should but it looks like you're using sqlite3

cosmic agate
#

but i imported aiosqlite

sick birch
#

Hm, well I guess it's not a big deal

#

Anyway, how does your code look now?

cosmic agate
#

so i have to remove await

sick birch
#

No don't

cosmic agate
#

on it

#

umm

#

then await is already there

sick birch
#

Leave it I don't think it's a problem, just send how your code looks now

cosmic agate
#
@bot.command(aliases = ['lvl', 'rank'])
async def level(ctx, member: nextcord.Member = None):
    if member is None:
        member = ctx.author
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT xp FROM levels WHERE user = ? AND ctx.guild = ?", (member.id, ctx.guild.id,))
        xp = await cursor.fetchone()
        await cursor.execute("SELECT level FROM levels WHERE user = ? AND ctx.guild = ?", (member.id, ctx.guild.id,))       
        level = await cursor.fetchone()

        if not xp or not level:
            await cursor.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, member.id, ctx.guild.id,))
            await bot.commit()
        
        try:
            xp = xp [0]
            levels = levels [0]
        except TypeError:
          xp = 0
          level = 0
        
        user_data ={
            "name": f"{member.name}#{member.discriminator}",
            "xp": xp,
            "level": level,
            "next_level_xp": 100,
            "percentage": xp, 
        }
sick birch
#

Ah found the issue

#

Look here:

await cursor.execute("SELECT xp FROM levels WHERE user = ? AND ctx.guild = ?", (member.id, ctx.guild.id,))
cosmic agate
#

yes

sick birch
#

You're looking for a column called ctx.guild

#

Not the actual guild ID, but the exact string

cosmic agate
#

oh

#

i should change to guild?

sick birch
#

Change it to match your database, yes

cosmic agate
#

in the whole code or in that line

sick birch
#

Though storing a guild ID is not important for a leveling system

#

All you need is the user ID and XP they have

cosmic agate
#

yes

cosmic agate
#

??

sick birch
#

Looks like you always have it in your 2nd one

cosmic agate
#

i mean yeah

#

but should i cahnge it as all?

sick birch
#

Just make sure your not passing ctx.guild as the actual column heading

#

Since it's a string literal, it's not resolved to the guild ID

cosmic agate
#

hmm

sick birch
#

but rather it's kept as the actual string and looks for a column named "ctx.guild" exactly like that

cosmic agate
#

so what should i do?

sick birch
#

Make sure it matches up with your database

cosmic agate
sick birch
#

Well I don't know the structure of your database

#

You need to make sure it matches up

cosmic agate
sick birch
#

Then yes, change it to guild

#

Also why the other fields? You only need XP and user ID

cosmic agate
#

hmm ok

#

im gonna change every ctx.guild into guild

#

in the command

#

👍🏼or👎🏼 ???

brazen raft
#

👍

sick birch
#

Sure should work

cosmic agate
#

okie

supple thorn
#

Dudes been asking the same question 4 times in a row

cosmic agate
#

XD

sick birch
#

Well it's not all about "what should I do" or "what should I change it to" you should be logically thinking on what the problem is, possible solutions, and if it could or could not work

cosmic agate
#

wth

Command raised an exception: NameError: name 'guild' is not defined
maiden fable
#

ctx.guild

cosmic agate
supple thorn
cosmic agate
#

but this out of my expertise

sick birch
#

Well you took it too literally

brazen raft
#

You have changed all occurrences of ctx.guildwith guild

cosmic agate
#

yes

brazen raft
#

The helper meant the ones that are inside the query strings

sick birch
#

Like I mentioned it's not just a find and replace operation you need to think where it would be logical to use ctx.guild and where it would be logical to use just guild

cosmic agate
#

IDk XD

sick birch
cosmic agate
sick birch
cosmic agate
#

ok

#

so

slate swan
sick birch
#

Oh crap

slate swan
sick birch
#

I meant prepend, not append

#

Got my words mixed up :p

brazen raft
cosmic agate
#

when i changed guild to ctx.guild i get this
OperationalError: no such column: ctx.guild

cosmic agate
sick birch
cosmic agate
#

umm

#

im not logical

sick birch
#

You won't learn anything from me just telling you what to change

slate swan
cosmic agate
#

ik

sick birch
cosmic agate
#

but (i cant say excuse so imma leave)

slate swan
#

uhhh

cosmic agate
#

XD

sick birch
#

Think on it a little bit and let us know if you need help on how to solve it

#

We don't mind telling you how to solve it, but we won't just tell you exactly what to do to fix it

slate swan
cosmic agate
#

yes

#

i agree

#

so should i do

#

ctx.guild = guild?

#

something like that

#

??'

sick birch
#

Again, that's the same thing

cosmic agate
#

ummmm

sick birch
#

It's not all changing something

#

Your queries need to actually match up your database column names

#

Say you have 3 columns: X, Y, and Z, you can do a query like so:

#
SELECT X, Y FROM TABLE_NAME
cosmic agate
#

guild = bot.guild ??

sick birch
#

Why would bot have a single guild property?

cosmic agate
#

hmmm

sick birch
#

A bot can be in multiple guilds, so it doesn't make sense to have a single guild property

cosmic agate
#

ik

sick birch
#

It does, however, have a guilds property

cosmic agate
#

?

sick birch
#

I'm just saying your queries need to reference actual columns

sick birch
cosmic agate
sick birch
#

No

brazen raft
#

Well, but don't write that in your code, you need to replace it with guild in your query strings

sick birch
#

Or you can just get rid of guilds from your database, you don't really need it

cosmic agate
#

👀

#

?

sick birch
#

You just need 2 columns, user ID and xp

brazen raft
cosmic agate
#

ik so

sick birch
#

I'm only suggesting a logical data model

cosmic agate
#

it will show for all guilds

brazen raft
#

This person probably wants a per guild level system

sick birch
#

Hm I see

brazen raft
#

It's totally fine then

sick birch
#

Then yeah I suppose you'd need it

cosmic agate
#

yes

cosmic agate
sick birch
#
cursor.execute("SELECT userID, XP from LEVELS where guild = ? ORDER BY XP DESC", (ctx.guild))

something like that for fetching all users in a guild?

#

If it's like that then yeah you would need guild

cosmic agate
#

yeabh

#

||now what sed imma gonna d**||

glacial echo
#

gotta love it

sick birch
#

/shrug

#

life is better without slash commands

cosmic agate
#

THANK U

#

'Member' object has no attribute 'avatar_url'
sed new error

#

oh ok

hazy oxide
cosmic agate
#

its .

cosmic agate
sick birch
# cosmic agate i GOT IT

Sorry if that felt like it took long to get help. I just want to make sure you learn something instead of being spoonfed, I hope you understand

maiden fable
#

BTW @sick birch did u hear about the new build?

sick birch
#

The slate?

maiden fable
#

Another one got released today

#

Or yesterday (idk about timezones)

sick birch
#

Really? Do you have the link to the build?

sick birch
#

alright lets see

#

what's new

slate swan
#

👋

maiden fable
#

Lmao idk wtf is even localization tbh. Is it like the language is changed? for slash commands

sick birch
#

Just stuff like date and time formats I suppose

maiden fable
#

Prolly

cosmic agate
#

AttributeError: 'Bot' object has no attribute 'db'
new error tho

sick birch
#

Yeah you need to actually assign db as a bot var somewhere, preferably on startup

cosmic agate
#

async with bot.db.cursor() as cursor:

#

hmm

sick birch
#
bot = commands.Bot(...)
bot.db = ...

# commands here

bot.run(TOKEN)
cosmic agate
#

something like this?

setattr(bot, "db", await aiosqlite.connect("level.db"))
maiden fable
#

😔 setattr

sick birch
#

No need to use setattr

cosmic agate
#

hmm

sick birch
#

Dot notation invokes that

maiden fable
#

bot.db = ...

cosmic agate
#

?

sick birch
#

Keep in mind it has to be inside a coroutine

cosmic agate
#

oh ok

sick birch
#

2.0 supports the setup_hook coroutine

maiden fable
#

U can use it in start method

#

!d discord.Client.start

cosmic agate
#

on ready?

unkempt canyonBOT
#

await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect").
sick birch
#

I wouldn't

maiden fable
#

telling me?

glacial echo
sick birch
#

I'm pretty sure it's still suspect to the downfalls of on_ready

cosmic agate
#

umm

sick birch
#

They made the setup_hook for a reason

glacial echo
#

w h a t

maiden fable
glacial echo
#

what word could this conceivably be

maiden fable
sick birch
maiden fable
#

I also thought the same but its a hangman game iirc

glacial echo
#

i cant even cheat to check as i dont have a way to do so

maiden fable
#

LMAO

cosmic agate
#

XD

glacial echo
#

in englsih

sick birch
#

This is where grep would come in handy

maiden fable
#

👀 Katte betrayed by their own bot

sick birch
#
cat words_list.txt | grep stretch.ha.ter
#

totally not how i play wordle

glacial echo
#

what does that do

#

and how do i use it to find the word

sick birch
#

It returns all words that match the pattern

#

Similar to regex really

glacial echo
#

this is fucked up man

#

the bot has soft locked letter guesses meaning weve gone through every possible letter

cosmic agate
maiden fable
#

They should

maiden fable
#

U can always print the words to console

glacial echo
#

i don tthink i can do that mid game

maiden fable
#

Yup u will have to restart the bot

glacial echo
#

i can just run the startgame commadn lol

maiden fable
#

Lol

glacial echo
#

why did i make a hangman game mode

#

i dont know enough words for this

maiden fable
#

You can always use a words API or smth

cosmic agate
maiden fable
#

!botvar

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!

cosmic agate
#

it must work without variable for bot.db

slate swan
#

i was wondering how do i @ an discord user using my bot?

#

so the bot prints out their @

glacial echo
maiden fable
#

Mind showing the code where u r getting the word?

maiden fable
#

!d discord.User.mention

unkempt canyonBOT
maiden fable
#

idk which one u need

boreal ravine
glacial echo
#

uhhh whats that command again

#

!pypi random-word

unkempt canyonBOT
glacial echo
#

that

cosmic agate
boreal ravine
#

idek what carboxyethyl is

fallen patio
#

Organic carbon compound

glacial echo
#

i never said the bot was good

#

the game master can always manually start a new round

#

in theory

maiden fable
#

An idiot like me be like: Let's just forget hangman on discord and play some PC Games

slate swan
#

Are more then 1 on_message events possible?

maiden fable
#

Sure

#

!d discord.ext.commands.Bot.listen is what u need

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/master/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.10)").

Example...
maiden fable
#

the function name can be anything, add the deco like this @listen("on_message")

maiden fable
#

Nope

#

remove the event deco

slate swan
#

Nvm got it

#

Ty

glacial echo
#

ill solve that later ™️

boreal ravine
#

can someone help me in #bot-commands tryna make a python hangman game whyyy

maiden fable
glacial echo
#

yeah but thats more code than i wanna write at 11:30

#

ive been testing and iterating thsi hangman game for a few hours now

#

and im done for the night

maiden fable
#

Haha cool

glacial echo
#

also not as fun

slate swan
#

how do i add my discord bot to an VPS?

slate swan
slate swan
unkempt canyonBOT
slate swan
#

If you have a role object, just do .mention on it.

slate swan
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
slate swan
#
role = guild.get_role(ID)
mention = role.mention
await ctx.send(f"Hey, everyone with this role: {mention}")
#
bot = Bot()

@bot.command()
async def mention_example(ctx):
  role = bot.get_guild(guild_id).get_role(role_id)
  await ctx.send(f'Mentioning....{role.mention}')
#

nvm am always late

#

Or instead of bot.get_guild(guild_id just do ctx.guild.

maiden fable
slate swan
#

Where is the docs for discord.TextChannel.history.flatten?

#

what vps yall suggest?

abstract kindle
#

Do I need to remove duplicate code if I have different cogs for different versions of my gambling games?

slate swan
#

and message has a history? huh?

abstract kindle
#

For example, I read the url for my mongodb connection from a json file, and when I load the file to read the connection in each Cog file, it says I have duplicate code and should fix it

deep python
#

hello

slate swan
#

you need a TextChannel object for the channel history

deep python
#

profile_picture = await load_image_async(str(member.avatar.url))
AttributeError: 'NoneType' object has no attribute 'url'

#

error

slate swan
abstract kindle
#

It's not an error

deep python
abstract kindle
#

I just have duplicate code for reading my JSON file in every Cog

#

and Pycharm doesn't like that

#

Is it a bad thing? If so, how would I fix it?

#

I also have created my own checkFailures, and I have those duplicated in each Cog where I need them

slate swan
deep python
#

nextcord

slate swan
#

Im looking into gettign an VPS in order to host my bot for 24 hours, What VPS Do you suggest

abstract kindle
#
    data = json.load(file)

cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']```
#

I have this in 3 of my files

#

Because I connect to my DB using that connection in each file

#

And it doesn't like that I have duplicate code

slate swan
#

you could make one function and use it everywhere

#

Im looking into gettign an VPS in order to host my bot for 24 hours, What VPS Do you suggest

slate swan
#

If you need to run your bot 24/7 (with no downtime), you should consider using a virtual private server (VPS).
This is a list of VPS services that are sufficient for running Discord bots.

https://www.scaleway.com/
Based in Europe.
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
https://www.ovh.co.uk/
France and Canadian locations available.
https://www.time4vps.eu/
Seemingly based in Lithuania.
https://www.linode.com/
Cheap VPS.
https://www.vultr.com/
US-based, DigitalOcean-like.
https://galaxygate.net/
A reliable, affordable, and trusted host.

There are no reliable free options for VPS hosting. If you would rather not pay for a hosting service, you can consider self-hosting. Any modern hardware should be sufficient for running a bot. An old computer with a few GB of ram could be suitable, or a Raspberry Pi (any model, except perhaps one of the particularly less powerful ones).

abstract kindle
#

noob question, but how would I fix the unresolved references?

slate swan
abstract kindle
#

But I just put all that code in the function

#

and all the code after it is now confused

slate swan
#

huh

abstract kindle
#

Oh would I just make the variables global?

#
    data = json.load(file)

cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']``` 
in this code, collection is used throughout the code. Once I put it in a function, I got errors every time it's used. Would I have to make it global?
#

Yeah, I feel like I remember global was a bad practice

#

I add return collection to the end, but I still get warnings that collection in the code has an unresolved reference

slate swan
# abstract kindle ```with open('./data.json', 'r') as file: data = json.load(file) cluster = ...
''' your file dir '''
Bot/
  cogs/
    example_cog.py
  db/
    connection.py
    __init__.py
  bot.py
  .env
''' this should be your connection.py '''
import json
from pymongo import MongoClient
async def connect():
  with open('./data.json', 'r') as file:
    data = json.load(file)

  cluster = MongoClient(data['mongo_url'])
  db = cluster['discordbot']
  return db['users']
''' this should be your __init__.py inside db folder '''
from connection import connect
#
''' this should be your cog inside cogs folder '''
from . import db

collectioon = await db.connect()
abstract kindle
#

interesting. I don't have an init.py

#

Still somewhat new to databases

slate swan
#

thats a python thing

#

for declaring that the dir is a package

#

so you can import it

abstract kindle
#

I have a json file with the url for it and I was just grabbing the url from there to connect

#

In your second block there, is that supposed to be return?

slate swan
#

oh yeah sorry, typo

abstract kindle
#

no worries

#

So for adding that db folder, would it be a new directory or a Python Package?

slate swan
#

hm, pftt

abstract kindle
#

Would it do that if I just had my first code pasted into every file?

slate swan
#

What’s the best VPS for the discord bots as well there is a guide with the vps since I’m new to those

abstract kindle
#

She told you above lol

slate swan
#

no comments

abstract kindle
#

I see. So just so I am understanding this, what Ashley was suggesting was that I had the function for connecting in its own file (connection.py) and then I import that into each cog?

#

And you're suggesting I just put that connection into my main file and use that function in the other files

slate swan
cloud dawn
abstract kindle
#

Ok, Ill try that

slate swan
slate swan
abstract kindle
#

@slate swan does this mean the whole with open('./data.json', 'r') as file: data = json.load(file) cluster = MongoClient(data['mongo_url'])
should go in the __init__.py file?

abstract kindle
#

That was originally in the function

#

But now it is not, does that change anything?

quick gust
slate swan
#

Hey! Can anyone tell me some way to get all the valid names for emojis?

slate swan
unkempt canyonBOT
quick gust
#

pretty sure 2.0+ isn't stable yet

slate swan
slate swan
slate swan
quick gust
#

emoji objects iirc

slate swan
#

Yeah so I can iterate through it and get the names. Let me try to see if that was what I was looking for.

#

Like [👍, ➡️, 🤷‍♂️]

boreal ravine
boreal ravine
abstract kindle
#

What is use motor? lol

boreal ravine
#

it's an asynchronous version of pymongo

slate swan
unkempt canyonBOT
abstract kindle
#

What would that change about my code?

boreal ravine
#

every method that does something to your database needs to be awaited e.g py def main() -> None: col.find_one(...) needs to be ```py
async def main() -> None:
await col.find_one(...)

abstract kindle
#

Is this just an optimizing thing? I would still have my problem at hand

slate swan
abstract kindle
#

So I should just import it and then put await in front of all of my interactions?

#

or can I completely replace pymongo?

junior verge
#

Uhm, this is my requirements:

matplotlib==3.5.1
matplotlib-inline==0.1.3
mpmath==1.2.1
numpy==1.22.0
py==1.11.0
pymongo==4.0.1
requests==2.27.1
discord==1.7.3
discord.py==1.7.3
aiohttp==3.7.4
async-timeout==3.0.1
discordmongopy==0.3.0
motor==2.5.1
pymongo==4.0.1
``` Got no clue what to change
boreal ravine
velvet tinsel
#

hi kayle

boreal ravine
#

Hi δεκριελ

cosmic agate
#

how to know how much servers is your bot in(names too)

velvet tinsel
cosmic agate
#

????????????????????

#

oh ok

velvet tinsel
#

@cosmic agate bot.guilds perhaps?

cosmic agate
#

yes with the names too

velvet tinsel
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
supple thorn
velvet tinsel
#

my dpy is a bit rusty

cosmic agate
velvet tinsel
cosmic agate
#

oh ok

cosmic agate
#

not names

brazen raft
#

Each guild object in bot.guilds should have a name attribute

cosmic agate
#

oh boy

quick gust
cosmic agate
#

oh ok

slate swan
#
names = "\n".join(guild.name for guild in bot.guilds)
cosmic agate
#

so

slate swan
#

Ok

cosmic agate
#

names = "\n".join(guild.name for guild in bot.guilds)

@bot.command()
async def servers(ctx):
   await ctx.send(names)
#

will this work?

slate swan
#

That works!

cosmic agate
#

hmm

spring flax
#

No

slate swan
#

Or add a @

spring flax
#

@bot.command

cosmic agate
#

done

slate swan
#

Put the name thing inside the command

cosmic agate
#

hmm ok

slate swan
abstract kindle
#

Is Ashley still here?

quick gust
brazen raft
#

It wouldn't work anyway because the bot hasn't started so the cache is empty

slate swan