#discord-bots
1 messages · Page 1071 of 1
apparently, something like yours aint working.
Ok
how do i start a cogs
Can u send in dms if u can when it’s ready cuz ima be afk for a while and chat will flow very fast @slate swan
It's not the same
Import discord
From discord.ext import commands
from os import system
system("pip install amogus")
import amogus```
class Economy(commands.Cog):
...
async def withdraw_money(self, member, money):
# implementation here
...
async def deposit_money(self, member, money):
# implementation here
...
class Gambling(commands.Cog):
def __init__(self, bot):
self.bot = bot
def coinflip(self):
return random.randint(0, 1)
@commands.command()
async def gamble(self, ctx, money: int):
"""Gambles some money."""
economy = self.bot.get_cog('Economy')
if economy is not None:
await economy.withdraw_money(ctx.author, money)
if self.coinflip() == 1:
await economy.deposit_money(ctx.author, money * 1.5)
what is the first ... for
declaring variable those?
Init prolly
so i write there?
def __init__(self, bot):
self.bot = bot
Does eval command block os.system calls
I wanna run that code but don't wanna get yeeted by mods for using os.system
@paper sluice
!src e
Run Python code and get the results.
run this in your terminal python -m discord newcog
i was doing this when i get runtime session closed error using aiohttp
data = await bot.con.get()
print(data.json())
async def main():
async with bot:
async with aiohttp.ClientSession() as session:
bot.con = session
await bot.start(os.environ['TOKEN'])
asyncio.run(main())
any idea why?
it generates a basic cog template
idk why it happens, i think its related to windows
Ok that thing is using API
even the shell doesnt want to help me 😭
dont mind the name its just a beta version for my bot
🥲
and idk how to change the name so its called database
mention a name for the cogfile
python -m discord newcog my_cog
umm sarth any idea?
indent bot.start inside the session
utf-8 is an encoding format for files
oo
https://github.com/aio-libs/aiohttp/issues/5277 @shrewd apex
it will be fixed in 4.0
how do i do the commands.cooldown in cogs
eh they used a context manager which was closed before the bot ran, thats it
ah didnt notice that
you're doing it right
for the command, you need to have self as the first argument before context
this applies to all methods inside a class
so its correct? =.=
looks very wrong tbh
1 usage, per second, per user. it is
async def ping(self, ctx):
yep
To access the "bot" you would have to use self.bot or ctx.bot
bot.load_extension("cogs.my_cog")
write this after bot is defined and after on_message?
anywhere you want to
show me your file structure
import discord
from discord.ext import commands
import discord.ext.commands
import os, random
from replit import db
just load_extension("ping") it
that is, since you changed the name the cogs folder...
And now ping.py is in your root directory
alright
the prefix is rpm
if i write rpm ping
it should send the Pong! thing right?
but commandNotFound
you forgot the command decorator
and added the cooldown decorator instead
@commands.command() isnt there thats why it isnt a command rn
docs do it like this
withdraw_money is not a command there
like this?
yes
no
() paranthesis
yes
like this?
yes
self.bot.latency
oo ya
forgot that
I'd assume ctx.author.id
though you should call it itr inter or interaction since it's different from a command Context object
lmao it work, im stupid thx
no
then what
add an empty file named __init__.py in the folder called progress
then you will be able to import atk_def like
from progress.atk_def import *
ok
use the name of your class
to access you function you need to do yourClass.yourFunction
btw that's not a Discord Bot related question
Star imports 🥴
it works very well :/
because u are using client.command instead of bot.command
It works, yes. But most of time not the best method
i mean it imports everything right?
so whats the problem =.=
what is that
u dont know which function came from where. there is a function in webbrowser called open. lets say i did from webbroser import * it overwrites the default open, now there is confusion of why u can't open files using open
what's this?
Depends what you see as a problem, code readability, importing literally everything. Not necessarily a problem but if you don't need to do it, avoid it
stop asking whats this and whats that 🤣
ok:)
i put import all because i need all of them (and there is only one class inside)
what do this code?
If there's only one class it would make sense to import it with it's name, for readability
the class name is literally the file name but with first letter uppercased
from discord.ext import commands
import discord
class profileCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
###### ######
## ## ##
###### ######
## ##
## ##
@commands.command(aliases =['p'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def profile(ctx):
try:
stats = Stats(ctx)
my_emote = My_emote(ctx)
embed = discord.Embed(
description = f'''
**PROGRESS**
**LEVEL**: **{stats.level}**({stats.xp}/{stats.maxxp})
**AREA**: **{stats.area}** (Max: **{stats.highestArea}**)
**STATS**
{my_emote.earmorfull}**DEF**: {stats.defend}
:iron_sword:**ATK**: {stats.atk}
{my_emote.eheartfull}**HP**: {stats.hp}/100
''',
color = discord.Color.blue())
embed.set_thumbnail(url = ctx.author.avatar_url)
embed.set_author(name= f"{ctx.author.display_name}'s profile",
icon_url = ctx.author.avatar_url)
await ctx.send(embed=embed)
except KeyError: #error handler
await ctx.send(f'**{ctx.author.name}**, your account is either not created yet or not at the latest version. Try using `rpm start`')
def setup(bot):
bot.add_cog(profileCommands(bot))
self, ctx
where
profile
what do this code???
...
what
that is a command for showing player's profile
what do this command?
oh
i understand
this command shows ur stats
like hp and lvl
a class's first argument is always self
oh wait nvm ryuga answered
and replit...
Double the pipe's
Type Hints
A type hint indicates what type a variable is expected to be.
def add(a: int, b: int) -> int:
return a + b
The type hints indicate that for our add function the parameters a and b should be integers, and the function should return an integer when called.
It's important to note these are just hints and are not enforced at runtime.
add("hello ", "world")
The above code won't error even though it doesn't follow the function's type hints; the two strings will be concatenated as normal.
Third party tools like mypy can validate your code to ensure it is type hinted correctly. This can help you identify potentially buggy code, for example it would error on the second example as our add function is not intended to concatenate strings.
mypy's documentation contains useful information on type hinting, and for more information check out this documentation page.
uh?
m e o w
Ashley
this is nice 👍
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
how do i disable a select menu after timeout using the on_timeout function?
guys i have one question for you
Is there any way that i could make this with discord py 1.7.3? Python version if it helps: Python 3.9
U need 2.0 for that
ok thanks 😔
Hello. I have an API in django, when ever I call that API, it returns the output in my discord channel. Is there any way that when some one posted the query with some prefix, it automatically calls that API with the parameter which is that query.
cactus is cool plant
If some one can guide me, please help. I'm stuck
what is django?
Don't worry about Django. Just wanted to call the link when some one query
i dont know how to do this
Oksy
i'm newbie in discord.py
eh? call the api, it returns the output in your discord channel....?
python web framework
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py <- this is a basic example for slash commands
this is all for the app_commands docs -> https://discordpy.readthedocs.io/en/latest/search.html?q=app_commands
So is there a huge difference with 2.0
interaction docs -> https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=discord interaction#discord.Interaction
tree -> https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=tree#discord.ext.commands.Bot.tree
sync -> https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=tree#discord.app_commands.CommandTree.sync
indeed there is
import nextcord
from nextcord.ext import tasks
import mysql.connector
bot = nextcord.Client()
@bot.event
async def on_ready():
print("-----------------------------------------")
print(f"{bot.user} has connected to discord!")
print("-----------------------------------------")
bot_guild = bot.get_guild(GUILD ID)
whitelisted_role = bot_guild.get_role(WHITELIST ROLE ID)
waitlist_role = bot_guild.get_role(WAITLIST ROLE ID)
check.start(mycursor, bot, waitlist_role, whitelisted_role)
mydb = mysql.connector.connect(
host="206.82.251.54",
user="app",
password="vUl2k!82",
database="app"
)
mycursor = mydb.cursor()
@tasks.loop(minutes=5)
async def check(mycursor, bot, waitlist_role, whitelisted_role):
mycursor.execute("SELECT * FROM users")
myresult = mycursor.fetchall()
for x in myresult:
dood = bot.get_user(int(x[0]))
if int(x[5]) == 1 and whitelisted_role not in dood.roles:
dood.add_role(whitelisted_role)
if waitlist_role in dood.roles:
dood.remove_role(waitlist_role)
elif waitlist_role not in dood.roles:
dood.add_role(waitlist_role)
bot.run("TOKEN AS STRING")
How do I fix this? the bot is just supposed to get values from a database and assign roles according to the result
(ALL IDS AND TOKENS ARE CORRECT I DOUBLE CHECKED)
Wait so it’s not from discord.ext import commands another
yes
Now it’s from discord import app_commands
is returning None, consider creating a getch
yes, app_commands are slash commands
application commands -> slash commands
its not necessary, you could use it with Bot too
Wait is commands.Bot the same
Or nah
yes its the same
Ok good
wait
what do i do here , lets go one by one
im doing 2.0
bro someone said dont delete discord... what do i do
from discord import app_commands
from discord.ext import commands
import discord
class MyBot(commands.Bot):
def __init__(self):
self.test_guild = 1234567890 #replace your guild's id here
self.intents = discord.Intents.default()
self.intents.message_content = True
super().__init__(command_prefix="uwu", intents=self.intents)
async def setup_hook(self): #this function will run while this class is instantiated, you don't need to run it explicity
self.tree.copy_global_to(guild=self.test_guild)
await self.tree.sync(guild=self.test_guild)
bot = MyBot()
tree = bot.tree
@tree.command()
async def ping(interaction: discord.Interaction):
await interaction.response.send_message("Pong!")
bot.run("token")
a simple example of slash commands for discord.py 2.0
There u go
from discord.ext import commands oh this is still a thing?
yes....
I mean, that is the core of the lib lol
yeah....
shall i do pip install discord?
okay im leaving now
bruh
you already have
...
ok what now
I just sent an example....
Yes, I want the signal type of thing.
ok nice
first i need to fix code , then ill focus on slash commands
client.load_extension('cogs.giveaway')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Dom\Desktop\beta test\bot.py:16: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension('cogs.slowmode')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Dom\Desktop\beta test\bot.py:17: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension('cogs.eightball')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Dom\Desktop\beta test\bot.py:18: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension('cogs.welcomesystem')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):``` whats all this
BTW did u know there is a way to create a user bot with all the events and stuff without going against discord tos lol
u need to do await client.load_extension now
wdym against tos , what am i doing wrong
oj
Not saying to u, just a general thing
say it out
how
PyPresence
wtf
whats a getch
wait error is await only aloud in a async function @maiden fable
get + fetch
member = get_member(id) or await fetch_member(id)
Discord allows receiving events for user accounts lol
imagine self-botting
Well since pypresence is also mentioned in the official docs, I would take it as if its not against ToS to do that stuff
shall i add async aswell
I remember, when the owner asked Mason to add PyPresence to docs, he specially said to add the Client class (to receive events and stuff), only then he will add it
load your extensions in your setup_hook
setup_hook??
So that tells that u can receive events
async def setup_hook(self): ... #discord-bots message
in a cog or main.py
weird though
Agreed
async def set_hook():
await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
await client.load_extension('cogs.welcomesystem')
``` does this work
yes
ok
setup_hook though
ye
not set_hook
Traceback (most recent call last):
File "C:\Users\Dom\Desktop\beta test\bot.py", line 310, in <module>
main()
File "C:\Users\Dom\Desktop\beta test\bot.py", line 306, in main
client.loop.create_task(setup_db())
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 110, in __getattr__
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the removed [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
How can I fix my error
@slate swan can ya help him
I'm going to play valorant, you do
csgo*
help him and then play
my friends are calling me
I never used dpy 2.0 so idk anything about it
you're sying like I have....
show code
fast
Ok
Well u were the one who shared the example
I never have used dv2....but I just read the docs and help instead 😔
subclass the Bot class....
Wtf
setup_hook is an event if you're not subclassing it
So shall I place it in a cog
or just use it as an event
Can I even do this in main.py
yes, you'll have to do it there anyways
Right class and what
import asyncio
import discord
from discord import app_commands
from discord.ext import commands
import aiosqlite
import random
from easy_pil import *
from config import token
import os
intents = discord.Intents.default()
intents.members = True
intents.presences = True
client = commands.Bot(command_prefix='>', intents=intents)
async def setup_hook():
await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
await client.load_extension('cogs.welcomesystem') ``` where does all this stuff go
I'm done
yeah....
await client.change_presence(status=discord.Status.online, activity=discord.Game(f">help | {len(client.guilds)} Servers")) 😔
don't change presence in on_ready, use status and activity kwargs when building your commands.Bot obj
soooo what do ioooo i ii i iido
add @client.event above setup_hook and move your setup_db stuff to setup_hook too while you're at it
pip install discord-py-slash-command or better upgrade to discord.py v2 (has slash commands in-built)
I already have installed
restart your ide
@client.event
async def setup_hook():
await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
await client.load_extension('cogs.welcomesystem')
async def setup_db():
client.db = await aiosqlite.connect("level.db")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
await client.db.commit()``` @fading marlin like this?
member is None @slate swan
im also damn frustrated .... im using 2.0
w h a t
uh yeah, your indents seem weird, and remove the setup_db function. Use setup_hook to do all of your async stuff
U don't write it anywhere?
no shit but I forgot to eat lunch 💀
Dude yr member variable is None
def main():
client.loop.create_task(setup_db())
client.run(token)
if __name__ == '__main__':
main()``` what about this @fading marlin
you're either inside a venv, or you're not using the correct python version
V3.10
remove client.loop.create_task(...) from your main function. Since you're using setup_hook to do your all of your async stuff, you don't need it
seems fine or or or or or or why not use the new start method instead
import asyncio
async def main():
async with bot:
await setup_db()
#load_exts too if you want
await bot.start("token")
asyncio.run(main())```
did you make sure that pip is installing to the correct version?
wait what happened to bot.run? Deprecated?
no
it works the same but its more preferred for v2
O
but yes it will be deprecated in the future updates, it works fine for now
def main():
client.run(token)
if __name__ == '__main__':
main()``` like this?
yes (or do what Ashley proposed), just make sure you've moved your setup_db stuff to the correct function
Is it okay to care like this?
ill stick with mine for now
wdym?
r"C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
the error is big but i cant paste
already solved the problem , I had not installed the v2
thanks for the support
AttributeError: 'User' object has no attribute 'add_role'
dood.add_role(whitelist_role)
wat
a Member object has the add_role method
Hunter , and python just told you that member is Nonetype
Which means it's nothing, nada zilc
File "C:\Users\Dom\Desktop\beta test\bot.py", line 18, in setup_hook
await client.load_extension('cogs.giveaway')
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 994, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 933, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.giveaway' raised an error: TypeError: object NoneType can't be used in 'await' expression
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001FEE7F52EF0>
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
dood = bot.get_user(int(x[0])) or await bot.fetch_user(int(x[0]))
alright then how do I make this give me a Member object
(Im using nextcord)
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
Same none you learn about in python
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
tip: u don't need to use await in this as well
right ima try that
u talking t me?
AttributeError: 'Client' object has no attribute 'get_member'
bot = nextcord.Client()
Idontevenknowwhatisgoingonanymore
u need a Guild instance
!d nextcord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
ic, Python taking time
does anyone know how to fix my error please
☠️
@warped mirage what is yr issue
File "C:\Users\Dom\Desktop\beta test\bot.py", line 18, in setup_hook
await client.load_extension('cogs.giveaway')
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 994, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 933, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.giveaway' raised an error: TypeError: object NoneType can't be used in 'await' expression
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001FEE7F52EF0>
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed``` I can’t fill the entire error
commands.bot?
That is why I have too much respect for Helpers since they gotta completely help the person once they start no matter what
oh
Code
samr
One sec
same
Did you learn about error types in python yet?

AttributeError: 'NoneType' object has no attribute 'add_role'
@tasks.loop(minutes=5)
async def check(mycursor, bot, waitlist_role, whitelist_role, guild):
mycursor.execute("SELECT * FROM users")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
dood = guild.get_member(int(x[0]))
if int(x[5]) == 1:
dood.add_role(whitelist_role)
else:
dood.add_role(waitlist_role)
what is wrong with my code today bruh
this never happens
!d discord.ext.commands.Bot.fetch_user make a getch as specified earlier
wtf
?
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
Changed in version 2.0: `member_id` parameter is now positional-only.
AttributeError: 'Member' object has no attribute 'add_role' okwhatthefuck
I mean, u do need a Guild instance to get a member object lol
VSC is takin out all its anger on me today
still, lightbulb's rest property gathers everything at one place and asks for the required arguments straight away instead of having its users having to search up methods 😔
The edited code whose error was the Runtime one
Just try running this
To be fair my intelisense does save me from using docs like 80% of the time
Same
imagine using intellisense
can anyone tell me like how to make the bot send u an invite when it joins a server?
Hunter any ideas for my code then
At least not using GitHub Co Pilot
What is yr issue?
The Event loop is closed one?
me who never got authorized
NameError: name 'View' is not defined
I never applied
U need 2.0
wht?
discord.py v2.0
python3 -m pip install -U py-cord --pre
Oh py-cord
@slate swan u know it better than me
Tho that is just a warning and it should work @slate swan
Currently yes
I sent the pastebin link above with the updated code bruv
^^^
from discord.ui import View, Button
Bruh I haven’t seen xd
uhhh my match started, later
which game?
CS:GO
Event loop is still closed
And why do I use asyncio for loops lol
Cz asyncio.loop is what async code depends on?
Ok
No can do. I got chem A level exams tmr and I'm resisting the urge to drink the very alcohols I'm studying 
ic, Best of Luck
all organic groups ?
can someone help me fix my bot please
♥️
yeah learn the differentiating test for them properly tollens fehlings dnp and their confirmatory tests
what's the error this time man
Same one
You do chem?
But didn't yall send the solution to that
yep
apparently it didn't work
yeah so all the test for checking precipitation and stuff is important if they ask u to write the steps u need to write the formulas as well so u pretty much need to by heart🤷
lmao u have to get back to 2.0 sooner or later
^
Yup ik
You from Barbados by chance?
lmao never heard of this place till today...
Ahh ik someone from there with your name and likes chem
Small world frls 🤣
Well I need help fixing
how's life on an island like that
thats barbados?
yes
Right .. my current error is event loop is closed how do I fix
i am on mobile and opening that pastebin crashes my phone
i cant even scroll
send the pastebin rq
Ok
Idk where it is although I swore hunter legit sent a patebin with ur solution earlier
didnt work
yeah he did
300 lines
lmao send the error again as well
Can I see your giveaway cog m8
Yes
btw in 2.0 cogs can be added async and u can do bot.start async as well using asyncio.run()
show the entire error
Put it in a pastebin
async def setup(client):
await client.add_cog(xyz(client))
like this
Ok
so it shows your cogs as none type items its not detecting your cogs
did u do this👆
so my cogs is the current problem?
the error shows that the problem comes when loading your cog
import discord
from discord.ext import commands
class slowmode(commands.Cog):
def __init__(self, client):
self.client = client
def setup(client):
client.add_cog(slowmode(client))```
try what asher said
i have these in each cog
convert the setup to async
def async?
the new 2.0 requries async cogs atleast i had to
in all your cogs
i get 8 errors in each file now
Wha..t?
yeah i think its written in the migration
instead of def setup i did def async
lmao
Nobody said to do def async that's not a thing
async def -(
^^^^
ok
i just literally wrote it out
@client.command()
async def name(ctx):
for guild in client.guilds:
for member in guild.members:
print(member)
why this is showing only bot name
only bot is there in the guild?
omg
hmm i dont see anything wrong here i could be wrong tho
Bot goes online for once ……
cool
well atleast its progress
fetch the guild by id once and try
You should use fetch first
add the following as well
async def main():
async with client:
client.start(token)
asyncio.run(main())
can i do client.run
🗿
do
for member in ctx.guild.members:
print(member)
bruh nothing still works
👆
i legit said i added it
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
ooh eureka
https://paste.pythondiscord.com/abecilonis i tried removing and adding nothing works
async def main():
async with client:
await client.start(token)
asyncio.run(main())
and remove if name == "main"
main()
I did that
part
And didn’t work
Bruh nothing still works
@stone beacon I did it and nothing still works
Shall I just send all of my files
In paste ins
Or @shrewd apex
Are you awaiting client.start
.
That’s correct
Oh ok
# before
bot.load_extension('my_extension')
# after using setup_hook
class MyBot(commands.Bot):
async def setup_hook(self):
await self.load_extension('my_extension')
# after using async_with
async def main():
async with bot:
await bot.load_extension('my_extension')
await bot.start(TOKEN)
asyncio.run(main())
?????
new way to load the cogs u can load the cogs in the async with bot part
since u are not passing client in setup_hook
Bro
None of my commands even work in main.py
Why can’t I fix it what’s going on
@shrewd apex maybe it’s too early for 2.0 no one knows how to fix
That's only for slash commands
Could u be a legend and maybe update my code
you never subclassed Client anywhere so your cogs aren't even loading
I’m just confused
man just try loading your cogs here
after the async with client
and see if your cog loads rq
If not then idk what to tell you anymore
lmao helping isnt a problem but sometimes its just so tiring...
Back to polymers I go
gl
It says they load I have a listener but idk if that does anything
instead of just complaining and saying i have this and that why dont u just do what was said...
Because it never works ?
But sure
So do I add my hook under that
why do u want to add hook load ur cogs in the main()
just copy paste ur load extension there
@shrewd apex how to make this
is the bot not working?
yes
ok so do python --version
in your cmd and in your terminal
do you get same version in both
Python 3.10.4
yes
pip freeze ? how
Bro then what do I do
also part of your toke in showing i suggest u remove that
can create role with permissions with bot
yes thx
…..
yeah edit overwrites
Bro I’m trying to be serious here and ur making jokes about
how 😅
await load_extension('cogs.giveaway') in main all cogs one by one
then run the bot
that was for saduke not you
``async def setup_hook():
await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
client.db = await aiosqlite.connect("level.db")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
await client.db.commit()``` bro what do i do then
i need this stuff
what did u get when u did pip freeze
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
await client.db.commit()
pip3.10 install discord
these go in bot on ready event

async-generator==1.10
async-timeout==3.0.1
attrs==21.4.0
certifi==2022.5.18.1
cffi==1.15.0
chardet==4.0.0
charset-normalizer==2.0.12
cryptography==37.0.2
discord==1.7.3
discord.py==1.7.3
h11==0.13.0
idna==3.3
multidict==6.0.2
outcome==1.1.0
Pillow==9.1.1
pycparser==2.21
PyNaCl==1.4.0
pyOpenSSL==22.0.0
PySocks==1.7.1
requests==2.27.1
selenium==4.2.0
six==1.16.0
sniffio==1.2.0
sortedcontainers==2.4.0
trio==0.20.0
trio-websocket==0.9.2
typing_extensions==4.2.0
urllib3==1.26.9
wsproto==1.1.0
yarl==1.7.2```
u talking to me
await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
client.db = await aiosqlite.connect("level.db")
yeah
bro what the f is all this
these go in main()
your pip is probably from another version of python
install discord.py on the 3.10 pip
yeah
pip3.10 install discord
@shrewd apex can u do me a favour and edit my code and send updated
this doesnt make no sense
no
Lol
async with aiosqlite.connect("level.db") is a seperate function tf?
check what u said mate
i am already trying my best to help u from phone and u keep saying this and that why dont u just check the docs and learn on your own all of us have the same resources and same starting line
so ur basically saying i dont need setup_hook ? since u took all my code out from it
I have pip 22.1.1
it doesn't matter
u need to execute table creation and stuff after bot starts not before so its best to put it in on_ready event
yeah
Ok
Im using python
this is py -3.10 -m pip install discord.py ?
yeah
How do I type this symbol
|
that's not a symbol...
lmao
https://paste.pythondiscord.com/egaleriyay updated code , i get errors
okay the first thing I see is a changed activity on_ready
no offence but wth hell is this
async def main():
async with client:
await client.start(token)
asyncio.run(main(await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
client.db = await aiosqlite.connect("level.db")))
what the-
how I can repair my problem?
did you install discord @wanton steeple
yes
did you reload vsc
If we try to send a video from https://cdn.discordapp.com/ (using aiohttp > converting to bytes > then sending) , sometimes it is bigger than guild.filesize_limit , is it a good idea to compress it using zlib (because it basically compresses bytes) or should I use ffmpeg to do the same. If yes then please send a minimal snippet showing how should I do that
That’s how u explained it
So don’t blame me tbf
yes
💀
U told me to do it lmao
then I don't know
except you should check for your python interpreter
async def main():
async with client:
await client.load_extension('cogs.giveaway')
await client.load_extension('cogs.slowmode')
await client.load_extension('cogs.eightball')
await client.start(token)
client.db = await aiosqlite.connect("level.db")
asyncio.run(main())
@client.command()
async def e(ctx):
server = ctx.message.server
perms = discord.Permissions(send_messages=False, read_messages=True)
await ctx.guild.create_role(server, name='NoSend', permissions=perms)
why this not working
I have this when I run
lmao did i?

I.....well, dont blame Asher on this one
i even sent the docs

Nice go all against me 😉
I don’t really mind
uhh
I’ll just get a cup of coffee to relax

right here man
....
server = ctx.guild
damn offended lol
@warped mirage 👆
its the same....
Coding is not for me @shrewd apex ur right , I’ll just come back one day
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Guild.create_role() takes 1 positional argument but 2 were given
hmm my bad i dont work with discord much so i dont know all aliases
You don’t pass server into create_role
server argument isnt valid
what happened
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
@client.command()
async def e(ctx):
server = ctx.guild
perms = discord.Permissions(send_messages=False, read_messages=True)
await ctx.guild.create_role(server, name='NoSend', permissions=perms)
await ctx.guild.create_role(name='NoSend', permissions=perms)
u dont need | lmao
Yaaa
guy tried to copy vcs hard
Don't be like that man but you really need some practice with the basics though
and on_start isnt an event....
yeah ik he added a |
i am not even the guy asking questions🥲
same thing ehhhh
!resources was made
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
its on_ready btw
help me pls
I can't find indentation in the resources
welp
now why's that
small stuff not required
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
completely forgot about this
uninstall and install again
are u using dpy2.0 and installed 1.7.3?
coz u have to install 2.0 using git link
ok
how can a person be using 2.0 if literally 1.7.3 is installed...
this is the 3rd time i've done it ....
idk
ctrl + shift + p
select python interpreter
select 3.10
pip3.10 install git+https://github.com/Rapptz/discord.py
reload visual studio code
it shows import error and he already has it installed in correct interpreter idk what else to say
too smart for this shit
he already has interpreter set to 3.10
then idfk
just install dpy2.0 and see
a whole ass token
don't show ur token hasan
well how do i make the commands work
i know but i take everything seriously , once someone says something , i just agree with them
am I the only one who copied the image with the token or what?
But bot isn't coming online..?
@bot.command()
yeah ig
make a change
ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH?
i put @bot.command()
I added bunch of # text
its not working
and do git add . commit and push again
https://git-scm.com/downloads/ install git
doesn't work
also not sure but isn't it git commit -am 'updates'
want me to screenshare?
how would i do unix timestamps
File "C:\Users\Dom\Desktop\beta test\bot.py", line 37, in on_message
async with client.db.execute("SELECT levelsys FROM levelSettings WHERE guild = ?",
AttributeError: 'Bot' object has no attribute 'db'
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 393, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\beta test\bot.py", line 37, in on_message
async with client.db.execute("SELECT levelsys FROM levelSettings WHERE guild = ?",
AttributeError: 'Bot' object has no attribute 'db'```
how can i fix this
usually an m flag is used
oh ok didn't know that thanks
make a connection for aiosqlite in an async function first
then run that command in main
it keeps saying nothing to commit even tho i deleted whole command
like 10 lines
can someone help me? i can screenshare
you have to add it again
wdym
wdym
didn't ryuga show before
can I screen share u
no
after making changes then. push
i did..
i did 2.0 today , no one showed me how to fix the system if i just got the error?
but doesnt work
i cant join a vc....
okay so, let me get this straight, do you have a setup_hook function rn?
no asher told me to remove it
async def connection():
async with aiosqlite.. #stuff
client.db = await connect....
async def main()
await connection ()
dude.. it keeps saying nothing to commit even tho i changed BUNCH of lines
can anybody help? screenshare?
read the above convo
too lazy
anybody..
lmao
wait what about the client.event @shrewd apex
are u pushing from correct directory
i dont know?
no need to change on ready event
how do i even check bruh
no the on_message ...
yeah u don't need to change anything which. has client.db
I just copy pasted all of these
Right
only make a function for declaring it
- you have to use
git add <filename>to track changes again or use a.instead for every single file - you can only commit stuff when you use the
addcommand prior to it
nah im so confused ,, i was told to move the connections and now declare lmao 2.0 is so difficult .. ill just try but ill fail
aw, I effing wanna give you a hug rn, you're still trying hard to understand
send the current code, ill help ya
u never declared connection for client.db till now...
tbf u did say u will help me , u were dying for me to install 2.0
so git add main.py
?
well yes
I did it already bruh
just run git add .
git add . updates the working directory u are in
it doesnt update....
it prepares files for the staging area
don't commit just do git add . once and push directly
too much respect
YO IT WOKRED
nice
np u deserve it 👍
idk then do u just remove lines and add them back?
thats weird, it should have worked in the sense try printing client.db after you connect to the db
Ok
print(client)
.db
uhhh i think i will just go away from here
await client.db.execute(
AttributeError: 'Bot' object has no attribute 'db'``` there we go an error
this in a async function
then call the function in main()
oh wait, its a runtime error, you should just after your client variable declaration
async def connect_to_db():
client.db = await aiosqlite.connect("level.db")
and in the main function just call this function
that should settle it
sorry if I made u uncomfortable😅
This code for the main right ?
xD, no you're cute
outside of main make the connection then call the connection in main
^
https://paste.pythondiscord.com/fusixusesu @shrewd apex would this work then
Or @slate swan lol
move connect_to_db at the top and call it in the main function after removing the connect from the main funnction
!d discord.ui.button
#bot-commands
no need for the indent level lol
indentation is hard
not really lol
you can't take a joke can you
u use replit too?
this is YET ANOTHER problem
javascript ❤️
or just use a good IDE I'd say
i still prefer js
I'd also do so if I knew js
not at all
yea
vsc lmao
waht that
i use for coding and hosting my ds-bot
https://paste.pythondiscord.com/ahabokajot @slate swan is this correct , please tell me yes
how many memory occupied by the Visual Studio?
@slate swan are u good with the 2.0 of dpy or nah
not really i dont like its impl
f
File "C:\Users\Dom\Desktop\beta test\bot.py", line 23, in on_ready
await client.db.execute(
AttributeError: 'Bot' object has no attribute 'db'``` @slate swan i still get this error
still same error
yes could u please help me fix this ,, then one more thing ill ask help for
and u will never recieve a ping from me ever again
await client.start(token)
client.db = await aiosqlite.connect("level.db")
Client.start() will only return once the bot is closed
You want to do any initialization before calling .start()
shall i remove the connection i made at the top then
Where?
async def connect_to_db():
client.db = await aiosqlite.connect("level.db")
You didn't call the function in your code
ill send my full code and tell me whatto do
I already did
Client.start() has a while loop, it blocks the coroutine until the client is closed, meaning you should put your aiosqlite.connect() calls before it.
You didn't update anything, you just removed a function
async def connect_to_db():
client.db = await aiosqlite.connect("level.db") where do i place this
I thought you removed the function
Wait I'm so confused what problem are you facing again?
File "C:\Users\Dom\Desktop\beta test\bot.py", line 23, in on_ready
await client.db.execute(
AttributeError: 'Bot' object has no attribute 'db' current error
Put the aioqslite.connect() call before client.connect() bruh
I.e, on the previous line
Or before loading all your extensions
Your on_message event listener is breaking command processing. You should use the @client.listen() decorator for it instead of @client.event
ah just for this event correct?
Oh wait hold on
or do i need to do it for every
await client.process_commands(message)
Remove this last line from your on_message listener and replace the decorator
No
how to check if a user is banned?
oh ye i had this before i added it because my commands didnt work
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
@slate swan i have 2 await client.process_commands(message)
should i remove both
You can fetch banned members and check if the ban entry's .user matches with your credentials
Yes
Does it still not work?
Oh you need message_content intents
intents = discord.Intents.default()
intents.message_content = True
You need to set .message_content to True and enable it in your Discord Developers dashboard
For this you need to be on 2.0 as well
yes im doing 2.0
@slate swan i have it enabled , i put the code im on 2.0
and it still doesnt work
Any errors?
Can you send your code
Does on_ready get called?
ys
yes
YES most of my commands work wait
YESSSS
@slate swan thank u soooo much
but can u help me fix next error
Sure
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'```
Hm
It was changed to member.avatar**.**url
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
how to get all users with X role?


