#discord-bots
1 messages · Page 487 of 1
can u pass me a invite to ur server ?
Sure
it should be something like
x = on_member_join(member)
await x.send('dm')```
not sure tbh
Wrong
It should be
@bot.event
async def on_member_join(member):
await member.send('DM')```
can someone help me how do i fix this?
yeah thats what i meant
are you self botting ?
whats that?
hello, try this with sqlite3:
UPDATE member SET Pseudo = speedeux WHERE ID = 882348295710736424
and i got this:
sqlite3.OperationalError: no such column: speedeux
The column doesn't exists
she exist
(
ID int PRIMARY KEY UNIQUE,
Pseudo text,
Balance int DEFAULT 1000,
Earned int DEFAULT 0,
Lost int DEFAULT 0,
Post text DEFAULT 'Stagiaire',
Experience int DEFAULT 0,
Salary int DEFAULT 0,
Composition text DEFAULT '',
ContributePoint int DEFAULT 0,
Contribution text DEFAULT '',
ActyToday int DEFAULT 0,
ActyWeek int DEFAULT 0,
ActyMonth int DEFAULT 0,
Here int DEFAULT 1
)```
what are you trying to do?
can someone help me. how do i fix this?
hello how can i access my mongodb from a cog? do i need to setup a separate connection or is there a way to use the connection from the main bot file?
Not relevant to your question. but why don't you use postgres
Because sqlite thinks that speedeux is a column.
If you want it to be a string make it 'speedeux' (add single quotes)
!bot-var
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!
I try to update the pseudo column to speedeux for people whose id is 882348295710736424
not really used sql that much and decided to give mongodb a go
nobody gonna help me?
what do you want speedeux to be? a string?
You have passed in an invalid token
year it a string
if you want it to be a string then make it 'speedeux' (add single quotes) or else sqlite will think that its a column
print("name edit: ", new_name)
cursor.execute("""UPDATE member SET Pseudo = {} WHERE ID = {}""".format(new_name, member_id))
database.commit()```
the entire function
with "?" ?
yeah
cursor.execute("""UPDATE member SET Pseudo = ? WHERE ID = ?""", (new_name, member_id))```
ok thanks
anyone able to help?
what do you mean by "bae" 
Connecting the discord bot to gpt3 https://pythonrepo.com/repo/Cyclcrclicly-shirt-bot
yeah its very epic 
baby lol
oh
Did u even read the error
Improper means wrong so regenarate your token.
ok
i want to dm a user when they send a command like .check sfsdfdsfds
how do i do that?
await ctx.author.send('dsdasd')
hi
Heya
how many languages i can use to create discord bot?
like i can use c# to create discord bot
Any language that has a discord libary lolo
Pycharm
yeah
@river walrus you know?
I wouldn't recommend PyCharm ngl
Use atom or Visual Studio Code
at some point
bro i am using Visual Studio Code
Bro is Visual Studio Code better than pycharm
Javascript, Java, Python, Rust and some others, most languages have a libary, just check google
IMO yeah
ooh
yeah
yes but
but??
for only for python development i highly recommend pycharm
ooh ok
Nah tbh
if you are using any other languages and files too then vs code
still bro
Python is best for it
But you gotta wait for a proper lib to be released
Since the current big one is discontinued
then why pycharm created 😄
how to use pymongo across a cog?
Variable.
!bot-var
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!
It's a IDE, some people like it some don't
VSCode doesn't have decent Python auto-imports
PyCharm kinda does
Yeah, but VSCode is nicer and easier IMO
thanks :)
pycharm is very good for python
yes but pycharm provide lots of feautes
It's your personal choice.
VSC has better themes, but it's only an editor so
the linter is very helpful and accurate
pycharm is more confortable for python dev
Yeah.
Not everyone agrees lol
see
i use vs code for python-dev because i use azure
otherwise i'll would be using pycharm
for highly level creating application
work matter , what are you doing
.
hello i try to make a discord music bot and it give me this error (i am watch tutorial)
Python 3.8.2 (default, Feb 26 2020, 02:56:10)
run
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'run' is not defined
?play
File "<stdin>", line 1
?play
^
SyntaxError: invalid syntax
run
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'run' is not defined
Replit: Updating package configuration
--> python3 -m poetry init --no-interaction
Ignoring exception in command play:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/Bomby/music.py", line 25, in play
ctx.voice_client.stop()
AttributeError: 'NoneType' object has no attribute 'stop'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'stop'
how can i solve it
this apper when i try to play something
Show code
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def init(self, client):
self.client = client
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel!")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_channel.move_to(voice_channel)
@commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_obtions': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'] [0] ['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
@commands.command()
async def pause(self,ctx,url):
await ctx.voice_client.pause()
await ctx.send("Paused")
@commands.command()
async def resume(self,ctx,url):
await ctx.voice_client.resume()
await ctx.send("resume")
def setup(client):
client.add_cog(music(client)) @river walrus
Can somebody suggest me, how to create a command, which can user only use once a day.
like ".daily"
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!ytdl
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)
!paste (sorry)
https://paste.pythondiscord.com/urusizunah.py
When I click the NextButton, it prints 2 and then 1, but when I click PrevButton, it prints 1 and then errors out... It is not setting the page as 2, thus returning a KeyError that the key 0 isn't in the dict... How to fix it?
@river walrus if you want i cant screen share and explain what i try and what i do better
Hunter
Hi
Just a KeyError that 0 isn't there in the dict
!code
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.
because the page var isn't set to 2 on press idk why
Can somebody suggest me, how to create a command, which can user only use once a day.
like ".daily"
There, edited the message
!d discord.ext.tasks.Loop
Wait, nvm
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
cooldown
thanks :*
doesn't it take a check?
Yea by mistake read it as How to make something run once everyday
???
np
BTW @spring flax any idea?
yes one second looking at the code
Can I get help here?
Yea
Cool
also, may I ask why you aren't using dpy's buttons?
sure, lol
that's what you want right
async def interaction_check(self, intr):
return #idk how to do this.. maybe ctx.author == intr.author?```
how to check if the user interacting is the author ?
self.ctx?
and then check self.inter.author == inter.author
I want to be able to have a kind of money system for each server and I want verified purchases stored in a json file. Would anyone know how I can get the value of a certain object by serverID?
{
"ServerID": {"Purchase1": 1, "Purchase2": 0, "Purchase3": 1}
}```
Currently, I've unsuccessfully tried using this:
```python
def check_purchase(client, message, purchase):
try:
with open('json/Purchases.json', 'r') as f:
purchases = json.load(f)
return purchases[str(message.guild.id)]
except:
return '0'```
Sorry for ping, I meant to turn that off.
that's no dpy relation
database is what you need for better experience instead of using json
Hey @slate swan mind looking at the code?
and i'm not so familiar with that
yours?
I'm hosting through replit, and whenever I try importing database, it crashes.
I can
lmao see the code
@river walrus sry bro i am so dumb can you try to explain me what i do wrong is my first time codeing in python
mhm
what's up with it
thanks
replit is bad,
oh shit that's advanced af
Youtube_dl is no longer legal
Since it's against yt TOS
I don't have any other way to host 24/7.
related to discord bots atleast
you don't want me to toaster tag you
Getting an error while running this code:
async def embed_func(ctx):
embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
embedVar.add_field(name="** **", value=":emoji_1: :emoji_1:", inline=False)
embed = await ctx.send(embed=embedVar)
await asyncio.sleep(1)
embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
embedVar.add_field(name="** **", value=":emoji_4: :emoji_2:", inline=False)
embed.edit(embed=embedVar)
await asyncio.sleep(1)
embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
embedVar.add_field(name="** **", value=":emoji_3: :emoji_1:", inline=False)
embed.edit(embed=embedVar)
await asyncio.sleep(1)
embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
embedVar.add_field(name="** **", value=":emoji_4: :emoji_4:", inline=False)
embed.edit(embed=embedVar)
await asyncio.sleep(1)
embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
embedVar.add_field(name="** **", value=":emoji_3: :emoji_2:", inline=False)
embed.edit(embed=embedVar)
await bot.delete_message(embed)
embed_func()
The error says something like "embed_func missing one positional argument named ctx")
lol
Can anyone help?
so what your try block returning is a dict. so you can then access the dict.'s values using keys
@river walrus oh i not knowing that this is how the man from the tutorial saw how to make a music bot
read the error
it's legit telling u what u did wrong
Never watch yt for discord bots
Thanks, I'll do my own research on that now.
They suck
I know, but what do I pass on to the function? None?
why does he teach breaking YT ToS on YouTube
what the fuck
@river walrus thx for tips and have a nice day
Cooldowns
you bass a Context instance
same
So just ctx?
yes
if it's inside a command
Alright, thanks!
Also @commands.command() before the function definition
Yo @spring flax got anything in mind? I have been brainstorming this since like 30 min
full tb?
I know it is messy, sorry
nah, it probably ain't
self.paginator.paginator_embed.description = "\n".join(f"{key}: {value}" for key, value in self.paginator.paginator_dict[self.paginator.page])
KeyError: 0
I'm too meh
What does that do?
And this happens in the PrevButton class
Oh it isn't a command, just a function @river walrus
no documentation for 2.0
I'm dying
Lol
how would I even learn it like that NotLikeThis
h-h-hi h-h-hunter
well the keyerror is when you try to access a key that is not in a dict
Yea I know
and the reason is cz the page variable isn't getting set to 2 when the NextButton is clicked
I just don't know how to fix it
this is for prevbutton?
The error? Yea
u mean self.paginator.page?
yeah
When I click the NextButton then
1
2
after that, when I click the PrevButton
1
KeyError 0
So that tells me the value isn't updated
what's self.paginator.page though
The current page number
Oh mb
did you just do like self.paginator.page = 1?
in the init of the paginator class, yes... cz that is the key of the first value in the dict
uhh sorry can't see why it's happening
:c
I was thinking this was gonna be easy 
Breh I will have to use globals
I don't want to use them :c
😕
pip install discord.py[voice]
Thx
Well I think I have found a way, time to try it
TypeError: __init__() missing 1 required positional argument: 'bot'
any hints on this?
you didn't pass bot when you instantiated the class
Thing is, it's not even inside a class
then where
Wait
async def main():
Bot = CogManager()
await Bot.start(Token)
I still have to pass bot?
show where u defined CogManager
In the same file as this one
try using lowercase names btw
i only need to see the __init__ of it
class CogManager(commands.Cog):
def __init__(self, bot):
self.bot = bot
@watch(path='Cogs')
async def on_ready(self):
print ('Bot is ready.')
async def on_message(self, message):
if message.author.bot:
return
await self.process.command(message)
# Starting
async def main(bot):
Bot = CogManager()
await Bot.start(Token)
if __name__ == '__main__':
asyncio.run(main())```
I despise not capitalizing names
It's more of a habit
Yep, i'm trying out cogwatch
u don't even have a start method in your class
No idea of what I'm doing
1st, you're subclassing Cog and assigning CogManager to a Bot variable, which makes no sense
2nd, since it's not a subclass of Bot, you don't have the .start method
3rd, why are you using asyncio.run to run your bot when that's done automatically by the lib
4th, your __init__ takes bot as the param, so when you do CogManager() you need to pass bot
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
Alr
-
What's the viable option, then?
-
Same question as above
-
No idea, I took that from Github and it requested asyncio for some reason
-
I see, I'll fix that after I'm done reading something about cogwatch
1&2. instead of subclassing Cog subclass Bot, in other words commands.Cog => commands.Bot, you will need to do a super().__init__() and in there you need to pass the same params as you'd pass when creating a normal bot instance
-
don't blindly copy code you do not understand not even a little bit
-
why use cogwatch in the first place
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
Still.
I'm literally copying it because I'm trying to understand what even is it
ye
And why not?
first understand, then copy
Can't exactly understand something without trying it out
because you end up with a completely shit code that makes no sense like it just happened 🤷♂️
That's pretty much how I learn things, trying out
then it should work
Doesnt
hmm understandable
did u do it in the terminal
how to change status of discord bot like change it to don't disturb
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
ty
are you sure you're using the right python path
It's not like it's something permanent, I'm just trying to learn how to properly use it to eventually add it to my code
Pretty much testing
alr
Worked, ty
yw
but please at least have some basic knowledge before doing so, the code you just sent is completely broken and you should've noticed at least that
you probably have a process of it running
i use replit
Bot's literally too angry to die
then dont use replit
How does it work with listening
LMAO
Bc it shows an error
Finally it died
Turns out it wasn't too angry to die
any good hosting service 24/7 that doesn't require me to have a webpage open?
activity = discord.Activity(type=discord.ActivityType.listening, name="whatever")
await bot.change_presence(status=discord.Status.dnd, activity=activity
ty
a vps
a wut?
vps = virtual private server
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/> EU https://www.linode.com/> US/EU/Asia
https://www.digitalocean.com/> US https://www.vultr.com/> US
https://www.ovh.co.uk/> EU/Canada https://www.hetzner.com/> Germany
https://www.time4vps.eu/> Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.
there
jk
those are some good vps
yes but how to use them?
idk never used one
bro read the error it's basic error
where are you puttin it in ur code?
I see
send code
await needs to be inside an async function
!code
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.
it’s not really basic since it’s related to async programming
hmm understandable
how do i put continue it keeps saying 'continue is not properly in loop'
if "jpg" not in url or "png" not in url:
continue
Yo @spring flax (sorry for the ping), but the paginator is now working perfectly... I was just overcomplicating things for no fking reason
import discord
import os
client = discord.Client()
token = "HALL NO, YOU DON'T GET MA TOKEN"
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game('With Team Lunar'))
await client.change_presence(status=discord.Status.dnd), await client.change_presence(activity=discord.Game('With Team Lunar'))
print('Connected to bot: {}'.format(client.user.name))
print('Bot ID: {}'.format(client.user.id))
client.run(token, bot=True)
doesn't show don't disturb only playing with team lunar
i think you want pass here
continue only works in for and while loops
yeah i had pass before i was just trying to see if it works
thx
You are modifying presence 3 times
Use the function one time
And add the other kwarg
status
Could you explain more?
activity=discord.Game("with team lunar"), status=discord.Status.dnd
Two kwargs
You are changing your presence 3 different times.
Each one of the 3 is different than the others.
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
hmm
so like this
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game("with team lunar"), status=discord.Status.dnd)
print('Connected to bot: {}'.format(client.user.name))
print('Bot ID: {}'.format(client.user.id))
@dapper cobalt
Correct.
gives an error
class discord.Game(name, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that represents a Discord game.
This is typically displayed via **Playing** on the official Discord client.
x == y Checks if two games are equal.
x != y Checks if two games are not equal.
hash(x) Returns the game’s hash.
str(x) Returns the game’s name.
File "main.py", line 13
print('Connected to bot: {}'.format(client.user.name))
^
IndentationError: unexpected indent
Indentation error.
I don't know what indetation means sorry I am new to coding
and english is not my first langauage
@dapper cobalt
You should learn basics of Python before making a Discord bot.
I am doing so
Indentation is the tabs and spaces before words
Like if you had an if statement, the indentation would be like this most likely:
If x == y
Print("rawr")
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Could be a translation issue, said his first language isn't English
when you code 90% of the time it’s going to be english
or twice
4 spaces and one tab is not the same
Its just that your IDE turns tabs into spaces, usually 4
@slate swan Incredible
?
I've been googling for like
20 mins
and I couldn't find anything significant on cogwatch
¯_(ツ)_/¯
😂
!d discord.ext.commands.CommandOnCooldown.retry_after
The amount of seconds to wait before you can retry again.
that's just-
sheeesh
and in on_ready aswell
anyone knows how to disable a button when the button was created using ui.button deco.?
I mean how do i get that button object?
The callback, which is the function you decorate with that decorator has access to the button param which should be the first one
the button object gets passed in as a parameter
This will be the corresponding button
hello,what are some of the best resources to learn to code discord bots?
so how do i disable this?
button.disabled = True?
I tried this but doesn't work
Hmm should've worked, maybe you are doing something wrong not sure
Sorry, an unexpected error occurred. Please let us know!
ServerDisconnectedError: Server disconnected
Uh oh
I'd need to use await self.bot.fetch_channel right? laws = await fetch_channel(287435156720058370)
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
No, self.bot.get_channel
friends, patience and practice 👍
Summed it up pretty well
whats it do?
thank you 🙂
Everything that dpy has + slash commands + buttons + etc
Not yet implemented
But we will
For sure
buttons?
Yeah dank member buttons for example
Lemme try to find a good example
dm me, when you start it, im interested, in what it does 🤔
We already started
g2g 👋
Aight
Just looked at the client.py for your lib, I think its very messy imo and could use a cleanup
would anyone take a look at my code and try to figure out whats wrong?
is there a github
For an example, heres my early implementation for my own lib that I started a while back ```py
from future import annotations
import typing
import inspect
import asyncio
from .http import HTTPClient
from .ws import WebSocketClient
all = ("Client",)
class Client:
def init(
self, token: str, loop: typing.Optional[asyncio.AbstractEventLoop] = None
):
self.loop: asyncio.AbstractEventLoop = loop or asyncio.get_event_loop()
self.http: HTTPClient = HTTPClient(token, self.loop)
self.ws: WebSocketClient = WebSocketClient(self)
self.events: typing.Dict[str, typing.List[typing.Callable]] = {}
def add_listener(self, func: typing.Callable, event_name: typing.Optional[str]):
name = event_name or func.__name__
if not inspect.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine")
if name in self.events:
self.events[name].append(func)
self.events[name] = [func]
def on(
self, event_name: typing.Optional[str] = None
) -> typing.Callable[..., typing.Callable]:
def inner(func: typing.Callable) -> typing.Callable:
self.add_listener(func, event_name)
return func
return inner
async def connect(self) -> None:
await self.ws.start()
async def login(self, token: str) -> None:
await self.http.login(token)
async def start(self) -> None:
await asyncio.gather(self.login(self.http.token), self.connect())
Everything is neat and organized, I think you should clean your's up as it will make it easier to read
none of my friends know python they all use JS 😆
Just google it, that's what I did
oh
https://github.com/AA1999/Disthon/blob/4d84e56a48ca5d36e4772f073ed298b006240ec8/discord/client.py#L1-L8 imports def need cleaning
discord/client.py lines 1 to 8
from logging import Handler
import handler
import websocket
import aiohttp
import intents as intent
from os import getenv
import typing
import asyncio```
And is there a reason why you do getenv? Library shouldn't be handling that, rather the user does
Seems out of scope
ah yeah just looked it up it's messy
*although the client i made for the api is probably messier
I'm probably judging to much, I just like writing really clean code so
and why is loop a private attribute
if you really dont want people to change it, make it a read-only property
The start method here though is pretty big brain on me 
wouldnt this error import websocket i think it should be from . import websocket
https://github.com/AA1999/Disthon/blob/master/discord/client.py#L70-L76
Also why is this awaited? Shouldn't the coro be run separately as a task? Wouldn't this completely lock when multiple events are run at the same time?
discord/client.py lines 70 to 76
async def handle_event(self, msg):
event = msg['t']
try:
for coro in self.events[event]:
await coro(msg)
except KeyError:
return```
I think that should work, although I'd try going for the relative import as you run a lower risk of dependency hijacking.
Thanks for the help
I didn't design the client.py tbh
One of the collaborators did
discord/websocket.py lines 43 to 48
def keepAlive(self) -> None:
while True:
time.sleep(self.hb_int)
asyncio.run(self.heartbeat())
def on_websocket_message(self, msg: dict) -> dict:```
camel case then snake case?
And why are you using threading? If you did what I did in my example for websockets that stays alive
No need for threading
You'd be amazing as a critic for the codes we write, would you join the contributors?
if we ignore most stuff there then it would be a decent lib
also why, just why? asyncio.run and time.sleep
That handle_event is probably called from the websocket when a Dispatch event is received.
Why put that in client then?
Just leave the method in websockets lol
seems out of place and the name doesn't make sense
I'm not sure, maybe if the repo/lib as a whole becomes more stable/clean
Aight gotcha
I'm just picky when it comes to clean code/unclean
rn it definitely needs a whole rewrite
I also do the same for my package, the client gets fed to the websocket, which calls the event handler if a dispatch occurs (decompressing the data first and cleaning it up before giving it to the handler)

Inspiration from discord.py is always fine as well, as visible but sometimes its better to make your own impl
I'll take a look at the code, try to clean it up
async def dispatch(self, event: str, data: typing.Dict) -> None:
logger.info(f"DISPATCHED EVENT: {event}")
if event == "READY":
self.session_id = data["session_id"]
name = event.lower()
if name in self.client.events:
for callback in self.client.events[name]:
data = await self.parse_event_data(name, data)
await callback(data)
``` this is what I do
Just left it in websockets, kept the client void of any websocket stuff
Do you know anyone who's got experience with discord API?
it doesn’t really matter who knows the API but what matters is how you implement it
beginner question how do I make my bot go offline with discord.py?
In my case, this is mainly done for convenience sake, since you register events with Client, the function can easily call them, although you could likely do the same if you placed that event handler in the websocket.
anybody can wrap the API easily it’s not that hard
but if they do it properly or not is a whole other matter
@river walrus Should fix your user agent
https://github.com/AA1999/Disthon/blob/4d84e56a48ca5d36e4772f073ed298b006240ec8/discord/handler.py#L10
discord/handler.py line 10
self.user_agent: str = "Disthon test library V0.0.1b. User: sebkuip#3632"```
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
except for voice stuff tbh, that takes a special type of person

yeah
weird user agent....
lol user agent, i don’t even use one
same
Honestly it is a bit weird they say "must provide a valid User Agent" if they don't even check it or dish out punishment for not using it
yeah i just used defaults and not much
Well, if you're going to have a user agent, should at least be a good one
That's a placeholder, I am Implementing User
Is there any way to get member/user info from a DM failure HTTP exception? i.e the name of the user who caused the exception
Implementing User?
i think they're just referring to the user agent you're using when requesting data from the http api
.invisible
to make it appear offline
!d discord.Status.invisible
The member is “invisible”. In reality, this is only used in sending a presence a la Client.change_presence(). When you receive a user’s presence this will be offline instead.
I call it APIUser
We're implementing that
User is a bit different
how different is it
thank's a lot
anyone know much about the HTTP exceptions?
ctx.author gives you that ig
i don't think ctx.author would work in a HTTP forbidden 403 (error 5007), would it?
I believe it could because it'll reject you if you dont share a mutual server with that user or you're blocked
nope, discord doesnt give this at all
Well, if it is raised when invoking a command then yes
hmm, i'll experiment I guess 
it's raised during a member join event
@discord.ui.button(label="Page 1", style=discord.ButtonStyle.green)
async def page_one(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.message.edit(embed=self.page1)
button.disabled = True
```
the button is not getiing disabled , also I'm getting no error message in terminal
any solutions?
mmm my first guess is you probably need to do it before editing
otherwise I dont see where Discord is going to be told to update otherwise
also tried that
I have never used discord.py v2 though
oh
a = (response.json()['phone'])
payload = {
"phone": a,
"Content-Type": "application/json",
}
headers2 = {
"Authorization": r.json()["token"],
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"
}
r2 = requests.post('https://discord.com/api/v9/users/@me/phone', json=payload, headers=headers2)
print(r2.text)
heres my issue, im pretty much trying to send a request to verify my discord account through phone number
and for some reaosn when i generate the phone number it comes like +7865754864 with the country code at the beginning of it, then when i send that with the request, it says invalid phone number, i tried removing the +7 but it said invalid because the box where you select the country needs to be +7, and its default is +1, i dont know if i could change the language of the account, or something. idk if this is gonna make sense
btw im not using this for malcious purposes, just to let you know, im legit testing networking since im trying to become better at python and this thing wont work
please read all
that'll get you banned from Discord for doing that
because that's essentially self boting / automating the API
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Is there a built in function in discord.py to create an invite for your bot or would I have to do it another way?
i mean you can use the developer portal
Yeah but I was thinking of making a command
https://discord.com/developers/applications/<bot id>/oauth2
Oh
thats the link to the webpage btw
ty
not the link to invite it
how can i make a loop command for music
I'm guessing you're making a command to play music from youtube?
!ytdl
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)
and what could happen to me?
i need help in this
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(member.guilds)} members"))
i want it to be like it
i have that
just wait a sec
can you give me plz?
well you have watching already
@client.event
async def on_ready():
print('Bot online')
servers = len(client.guilds)
members = 0
for guild in client.guilds:
members += guild.member_count - 1
await client.change_presence(activity = discord.Activity(
type = discord.ActivityType.watching,
name = f'{members}'
))
Should work
so you just set the rest of the text how you like it
Its illegal im pretty sure
{servers} Server {members}
youtube sues you and you'll be out a LOT of money
think a few thousand to a few tens of thousands of dollars
well.. unlikely
can you send me that in the code?
well client.users is all users the client can see
Not Ilegal, just against Youtube TOS
copyright law
Well, yeah, if you're downloading copyrighted content
it is illegal
tos is legally binding
Yeah, guess if you put it that way
hey how can i call a subroutine through a cog?
can you give an example
on the main python code be able to call and run a subroutine thats in a different python file
Is this the correct way to handle the errors of events inside of a cog? I have a on_member_join event which can error when the bot tries to dm a member with closed DMs and I want the bot to send a msg to a channel when/if such a error occurs but I'm evidently not doing it right as it's not sending my msg but i don't know where I'm going wrong.py async def on_error(self, ctx, error): if isinstance(error, discord.HTTPException): if error.code == 50007: fail = await self.bot.fetch_channel(816480968830353458) # Your ID: self.bot.config.code_of_laws await fail.send(embed = error_embed(colour = self.bot.error_colour, description = f"I was unable to DM {ctx.author}, It appears this user has their DMs closed. Get them to check their *Allow direct messages from server mebers* setting under **Privacy and Safety**. I advise reaching out to this user yourself."))
do you have the event decorator above the func there?
nope
well there's your problem
that would be? never really touched error handlers b4
Realistically you would be looking in the hundreds of thousands of dollars or more for a big music bot like the ones they've been taking down recently
on_error is an event, so you wanna put @bot.event above that func there
due to the self it leads me to believe it's in a cog
so it's cog.listener
in that case
ah okay, that makes sense thanks
^^
A cog is just a class, if you have access to the cog instance you can call the subroutine like any other instance method e.g.
class Foo(Cog):
def my_method(self):
print("hi")
foo = Foo()
foo.my_method()```
ok thanks
Oh the joys of slash commands
but what if the cog is in a different python file?
okay so I have thispy @commands.Cog.listener() async def on_error(self, ctx, error): if isinstance(error, discord.HTTPException): if error.code == 50007: fail = await self.bot.fetch_channel(816480968830353458) # Your ID: self.bot.config.code_of_laws await fail.send(embed = error_embed(colour = self.bot.error_colour, description = f"I was unable to DM {ctx.author}, It appears this user has their DMs closed. Get them to check their *Allow direct messages from server mebers* setting under **Privacy and Safety**. I advise reaching out to this user yourself."))which to my understanding should work, except it's not sending the msg and I think it's getting stuck on the discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user which is the evnt it's supposed to be responding to
You can use bot.get_cog to get the class instance
you should really be checking if it's discord.Forbidden instead of checking if it's an exception then checking the code
also make sure that the error hasn't been propagated up and has an original attribute which contains the original error.
This tends to be why you see alot of error handler code having error = getattr(error, 'original' error)
whats a good combination of thunerz and python
im trynna name my bot
sorry this is my first time using cogs but im getting this error test=bot.get_cog.meanie() AttributeError: 'function' object has no attribute 'meanie' what am i doing wrong?
get_cog is a function that takes the cog name
which returns either the instance or None (if the cog doesnt exist)
If you want my advise dont name your bot your own name or todo with the language used really
not that it matters much
okay well I changed it to thispy @commands.Cog.listener() async def on_error(self, ctx, error): #error = getattr(error, 'original' error) if isinstance(error, discord.Forbidden): if error.code == 50007: fail = await self.bot.fetch_channel(816480968830353458) # Your ID: self.bot.config.code_of_laws await fail.send(embed = error_embed(colour = self.bot.error_colour, description = f"I was unable to DM {ctx.author}, It appears this user has their DMs closed. Get them to check their *Allow direct messages from server mebers* setting under **Privacy and Safety**. I advise reaching out to this user yourself."))Reason I'm checking the code is because as far as I am aware only DM failures cause 5007 and I want to only get those, if other stuff happens to be in it then fine but I want to minimise that. I tried that error = getattr(error, 'original' error) bit i obviously wsn't using to right bc it just gave me syntax errors
you missed a comma off the end of 'original'
sorry that was my bad 😅
also make sure another listener isn't consuming and silencing the error already
well i do have a more general _on_command_error, would that be affecting it?
and if so then I just check the error code in that handler and pass it right?
you can do that yes
but yes error handlers can and will affect each other if you dont re-raise / consume them
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
i mean i just don't get why discord is forcing slash commands
it just makes less possible and they are tedious to work with
I mean you need a decent framework for them to suck less
but they can be pretty neeto at times
the only upside i really see to it is that it makes it easier for users to correctly input everything
outside of that i don't see a single benefit
okay so i think the other handler is still consuming it unfortunately so i'm gonna call it a day bc it's getting late and come back tomorrow to troubleshoot.
just downsides
well what is it saying?
Nice for UI, Sucks to debug though on the HTTP side
okay well I would recommend not having a bare except
but for the purpose of debugging and time
add this import statement
from traceback import print_exc
and in the except block as the first line add
print_exc()```
and see what it prints in the terminal
okay so the api is rejecting you because your embed is invalid
which means the api is returning None for location (or maybe country_name I cant remember if discord accounts for indexing at 0)
your 7th field has a value that is missing
well the value is being passed, it's just None or empty
that discord doesnt accept
probably the best fix is using the or statement to see if it's a falsey value (None, False, Empty string etc...) and swapping it with some default e.g. "None"
!e ```py
foo = None
print(foo or "Hello")
foo = "Hello, World"
print(foo or "Hello")
@night crater :white_check_mark: Your eval job has completed with return code 0.
001 | Hello
002 | Hello, World
pass something to the embed field's value
im trying to do a download bar for my discord bot when it logs in theirs a download bar but nothin shows up
def start():
tasks = 10
x = 0
while(x<tasks):
time.sleep(1)
bar["value"]+=10
x+=1
percent.set(str(int((x/tasks)*100))+"%")
text.set(str(x)+"/"+str(tasks)+"tasks completed")
window.update_idletasks()
window.mainloop()
window = Tk()
percent = StringVar()
bar = Progressbar(window,orient=HORIZONTAL,length=300)
bar.pack(pady=10)
percentLabel = Label(window,textvariable=percent).pack()
text = StringVar()
button = Button(window,text="download",command=start).pack()
i have my doubts one can use TkInter with a discord bot
seeing as it's completely blocking and such
ok
should i do it on_ready?
wut?
should i do
def on_ready():
tasks = 10
x = 0
while(x<tasks):
time.sleep(1)
bar["value"]+=10
x+=1
percent.set(str(int((x/tasks)*100))+"%")
text.set(str(x)+"/"+str(tasks)+"tasks completed")
window.update_idletasks()
window.mainloop()
window = Tk()
percent = StringVar()
bar = Progressbar(window,orient=HORIZONTAL,length=300)
bar.pack(pady=10)
percentLabel = Label(window,textvariable=percent).pack()
text = StringVar()
button = Button(window,text="download",command=start).pack()
sorry but what
i dont know anymore
I dont think thats a Discord thing
i just told you that TkInter probably isn't compatible with discord.py at all
k
they want to do a download bar when the bot starts for...reasons
using TkInter
but i don't think that works like that
There isn't really any 'progress' other than shards starting

that too
If you really really want a UI like that then use Kivy with it's asyncio backend
but in reality it would be better to have a API where they relay it to a web server that then renders it as HTML for you
that would be something that would actually be possible yes, a separate application that communicates
depends what you want to do with them
If your bot doesnt absolutely need the gateway / websocket events then you can use a HTTP server approach
But there is quite a bit of boiler plate code and not many libs around really
I do maintain my own framework for slash commands designed entirely around the HTTP server side of stuff for minimal boiler plate though: https://github.com/ChillFish8/roid
OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 5432)
Getting this error from switching to Windows to Arch Linux, can't find a proper answer anywhere. Using asyncpg with postgres.
async def create_db_pool():
bot.db = await asyncpg.create_pool(database = "prefix", user = "user", password = "pwd")
print("Connected to database.")```
Thanks!
Apparently asyncpg cant connect to the postgres server
are you sure it's running / exposed correctly? (the db)
Yes it's running
also postgres servers need to be set to allow outside connections if you're connection from another computer
How could I do that?
in the postgresql.conf file
at the bottom there are the connection settings
for instance
# IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 10.1.2.28/32 md5
the top one being localhost and the bottom one being a random computer
- for all IPs if you want anyone to connect from anywhere
Alright thank you
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.
Imagine
how would i implement a mute command
how do i make anti invite?
It would probably because the request errors
Try it with a valid number code
Then try it with a wrong one
Oh yeah, usually APIs have somekind of a success key, like "success": True or "code": 400
Try adding it to the code
if success:
# do all the embed stuffs
else:
await ctx.send("There's something wrong")
Is anyone interested in helping me develop a discord bot for a strategy game that runs in the server? It's similar to those IDLE RPG bots.
if user_message.startswith('your'):
response = f'you're*'
await message.channel.send(response)
return
i got error
what's the error?
Where is user_message defined?
i keep getting a eol while scanning string literal in "eve" on event:
otherlist = ("-----bot-----", "-----version 1.0-----","0%| |","25%|███ |","50%|████ |","75%|███████ |","
100%|██████████|")
@bot.event
Is that supposed to be a list?
response = f'you're*'
^
SyntaxError: invalid syntax
f"you're*"
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
ayayaya ty
It's because your string is ' ' and you used ' in "you're".
thank u so much
Np
wrong quotes
ahh, already answered
yes
note, you can do this aswell 'you\'re'
[] and not ().
it still says the same thing
Show me your new code.
the code related to the problem:
otherlist = ("-----Nicebot-----", "-----version 10.0-----","0%| |","25%|███ |","50%|████ |","75%|███████ |","
100%|██████████|")
@bot.event
async def on_ready():
print("we have logged in as Nicebot and its ready to use.")
for x in otherlist:
print(x)
I said, otherlist = [] and not otherlist= ().
i did it said the same error
Can you show the full traceback?
doesnt even run it theirs a eol while scanning string literal
Show traceback.
it doesnt have a traceback it doesnt run the code
thats what it says
!e
otherlist = ["-----Nicebot-----", "-----version 10.0-----","0%| |", "25%|███ |" , "50%|████ |" , "75%|███████ |" ,"100%|██████████|"]
for x in otherlist:
print(x)
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
001 | -----Nicebot-----
002 | -----version 10.0-----
003 | 0%| |
004 | 25%|███ |
005 | 50%|████ |
006 | 75%|███████ |
007 | 100%|██████████|
@slate swan fixed.
you changed the () right cuz if you did i tried and it didnt fix it
You had an un-closed string. Probably you added the sentence in another line.
It just worked.
^
http://net-informations.com/python/err/eol.htm#:~:text=An EOL (%20End%20of%20Line,the%20end%20of%20the%20line%20.
which?
I'm not sure. I just re-wrote them all.
Hello
You may copy it if you want.
Why does @bot.group() not work on replit
Isn't it @commands.group()?
!d discord.ext.commands.group
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
!d discord.ext.commands.Bot.group
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
thx
No problem.
Did you first remove your default help command?
I believe so
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
help_command=None
discord.ext.commands.Bot has a help_command kwarg in which you can set to none
yup ^
Does the help command work?
question why [] in a list and not ()
But the help ping does not?
[] is for arrays.
Show me the code for the help ping.
It gives error
you have defined ping somewhere else
Yes
Oh yes, I forgot about that.
You've got another function called ping.
You can't have two functions with the same name. I think.
i recommend moving it over to a different file.
How?
!e
async def foo():
pass
async def foo():
pass
@dapper cobalt :warning: Your eval job has completed with return code 0.
[No output]
Use cogs.
do you know OOP?
mistake.
That's a bad way to make a Discord bot.
I think I can spoonfeed you a little bit.
But for $100.
It looked confusing
Just kidding.
k
I'll make a github public repository to be a template for using cogs. Give me a moment.
Sure.
Is there a reason as to why it might say that the emoji is unknown:
message = await channel.send('Hello world')
await message.add_reaction(':wave:')```
The message itself sends though
@heavy radish https://github.com/ScopesCodez/discordpy-cogs
Example for using cogs in discord.py. Contribute to ScopesCodez/discordpy-cogs development by creating an account on GitHub.
Didn't take me much.
Use the emoji's unicode.
@dapper cobalt
👍
What is it?
The line from class
is it supposed to be together? and keep ping on please
What happen here??

Why are you printing in the for loop? This will cause spam in your terminal.
Also what is supposed to be together?
I just copy pasted...
Oh dw. Thats just me being dumb
What is the error?
@bot.event
async def on_ready():
for cog in os.listdir(r"cogs"): # Loop through each file in your "cogs" directory.
if cog.endswith(".py"):
try:
cog = f"cogs.{cog.replace('.py', '')}"
bot.load_extension(cog) # Load the file as an extension.
except Exception as e:
print(f"{cog} is failed to load:")
raise e
print(f"Logged in as {bot.user}")
``` Indention Problem??
2 on_ready events?
I'll remove the other
Just copy the code and paste it.
Massive Load
why do u keep changing through f strings and .format
More like copy pasting through
Bruh
How do I get access to a message in which a reaction was posted on?
!d discord.Reaction.message
Message this reaction is for.
@slate swan Theres an in built help command you'll need to remove that one first
👍
!d discord.ext.commands.Bot.remove_command
remove_command(name)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to remove aliases.
Its a string btw
could you show the part of the code where you are trying to do this?
You do that in the python script itself
Not in the terminal
bot = commands.Bot (.....)
bot.remove_command('help')```

Quick question, is there a way my bot could get the ID of a user through an @ ping? Thanks
it needs an argument
In a message or a parameter?
.command("help)
message
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
I'll look into it thanks
Returns a list of discord.Member object for mentioned users.
discord.errors.ClientException: Callback for help command is missing "ctx" parameter.
``` Help command is in COGS
No problem.
Show your code.
which one
You forgot to pass self.
the command
do you have self?
no
Happy to help
If you're using the template I gave you https://github.com/ScopesCodez/discordpy-cogs then look back at it.
(ctx, self)
commands in cog :
@commands.command()
async def command(self , ctx ):
.....```
yeah because the command is in a class so add a self
Sir, its the default one. I've told u earlier
Did you remove the help command?
If yes , just rerun the bot
help_command=None ??
???
they did the remove_command method
It's a arg passed in commands.Bot
restart the bot
I know
Ow
Show the help command I guess?
In your commands.Bot add , help_command= None
@heavy radish You clearly ignored comments.
Hmmm, Yea I fixed it. Thanks
BTW, Can I name the cogs folder as COGs or COGS
Lowercase looks weird
Yes, but don't forget to change it too in the for loop.
Oki
@slate swan does it send both of your help command and the one you don't want to?
you have your bot running multiple times , close all the previous tasks and run it again
If it's vsc , you can do it thru the run option in the sidebar
ah
no problems
wsp yo
How can you make a bot with two languages? Example, English and Spanish
how do i make my list like this?
commandslist = ("bot commands(always start with the (#) prefix ):
command 1
command 2
command 3
command 4")
so when you send it it looks like that from up to down in the middle
Is it possible to host a bot in pythonanywhere for free?
are you talking about coding languages or languages people speak
what's i18n?
A translation module
languages people speak, that's why I led by example
Just add them?
I dont know why you had to ask it here
so that it works
But you can just add them
it's bots, right?
You are just adding words
It will work you dont have to ask it here
Ive checked the pinned post here and they say that those services are not good for that. For repl.it as an example you need to run a server for the bot to not die, repl.it kills the process in an hour if the bot is not used iirc, and also need another service to ping the server. I think you can have a free page in pythonanywhere. That's why i was wondering if someone can use that
so i want it to have 2 languages or even more, with command! lang
You could literally add gibberish and english and it would work
Yeah you can add that
If you want it to be by guild id or by user id
by guild
how does discordpy logging work in cogs?
discord-components
go to that server and ask them
thats a tuple and for the "list" thing use the enter key
No such thing as free hosting lol
Again. Replit ISN'T hosting site
Is it free though? Thats the question
Yes
it has free hosting but only for 28 days
:/
You said you were on replit though?
WTH I am hosting my bot for more than a month and I never got a warning
where is your bot right now? On heroku or replit??
google has 300 dollars plus 3 months free hosting
I can't use it
Is blocked for my country
And i can't use vpn
Is the other way around
Heroku banned my country. So i was asking if someone here have tried using pythonanywhere
whats pythonanywhere
PythonAnywhere only allows you to use http/s ports
Host, run, and code Python in the cloud: PythonAnywhere
So no websockets
They do probably, alongside the websocket for your bot
Lonely refusing to read discord components docs 

The discord bots don't use http?
How do you send a message to a specific channel
if you have the ID, you can use get_channel and send that way
So would the id be an int or str
int
That was me
You wanted to know what I did and if it works
Forgive me. But I forgot that conversation. Can you give me a TL;DR and if it worked?
Or do we move on?
Ummm....It worked..
what was wrong with it?
@umbral fossil it'd be something like ctx.author.roles
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
I'm confused. did you want to check before the command ran? or during?
if they want it after the command gets invoked , they may use py ctx.author.guild_permissions.administratorhttps://discordpy.readthedocs.io/en/stable/api.html#discord.Member.guild_permissions
ye
One of the great things about programming
wsp wsp
Yep
this sucks
Wouldn't you just do message.edit and basically put the same embed in except changing the variables?
