#discord-bots
1 messages Β· Page 905 of 1
object not iterable
await coro(*args, **kwargs)
File "main.py", line 116, in on_message
for webhook in message.channel.webhooks:
TypeError: 'method' object is not iterable
print channel.webhooks
<bound method TextChannel.webhooks of <TextChannel id=952786030644326401 name='antonment' position=7 nsfw=False news=False category_id=None>>
this
you are changing the member object in your function, it will not affect the member variable in your command
huh? its not returning a list?
wtf
oh wait, did you add await before channel.webhooks?
made me think of python2
ohh, so I should py return memberin the places that I change it?
channel.webhooks is an async method, so to use it you should do this:
for webhook in await message.channel.webhooks()
should do
member = your_function()
ah okay, thanks
yesh
hey bro i cant make a cmd which automatically detects channels with same name and dels them how to make that
should I make this function async? is there any benefit to doing that in this usecase?
use the on_guild_channel_create event, iterate thorugh the channle list of the server and check if some of them have the same name, if so, delete the channel
you need that the member change in that moment so no, you should do a normal function
what is the code
thanks
For how many seconds can I block the event loop aka block the connection to discord before I get disconnected
I'm going to be running blocking code so I need to know if I should just optimize it or run it in run_in_executor
?
yo, have stupid question. i have bot that sends message each hour, but i got for some reason timeout on discord API. code here: https://replit.com/@PogLop/notUsefulBot#main.py, and error message here:
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
thx m8ts
isnt it supposed to be async for webhook in message.channel.webhooks()?
how do i get the list of guilds my bot is in
bot.guilds
what is the type of status for offline
offline
str(...) == "offline"
yeah that
With async you declare an async function, with await you call an async function. async for should do an asynchronous iteration
it's not declaring a function
async isnt just for declaring functions
running blocking code isn't an option, look for async wrappers or run_in_exec
Why isn't it an option?
you don't want to have bad implementations
My bad didn't read it.
is there a way to make so a bot will remove all messages, in a channel, that are neither images nor gifs?
ofc
purge is what you're looking for
check if message.attachments is empty
lovely 
I'm not aware of an asynchronous wrapper for BeautifulSoup and run_in_exec is resource intensive so I would prefer to avoid using it
if you want it to remove messages in real time you just need to do the latter in an on_message
have you tried via requests before webscraping tho?
How is BeautifulSoup blocking
It's not
Oh so then I'm fine
in your case, you should
iterate through messages, check if message.attachments is empty, if not keep the message, otherwise delete it
Then why running it in thread pool executor
Because I was unaware it wasn't blocking?
You shud log stuff to check what's blocking
What do you mean?
Enable logging
think about beautifulsoup
as you would on .replace()
you ofc don't need an async wrapper to replace text
how do i make the bot add role when i run a command?
like if i want to add a role 'muted'
well given their Member object you can use member.add_roles(<your role object>), where the muted role's id could be used to get that role object (guild.get_role(343944376055103488))
if you're just adding a role thats basically it
oh ok tysm
add_roles is a coroutine 
this is in a on_message() 
if message.guild.id == 551544391395835914:
if not message.attachments: message.delete()
await
await message.delete()?
if message.guild.id == 551544391395835914:
if not message.attachments: await message.delete()
correct
hello
I wonder if the message.guild.id is correct though 
it would check if the message is in a specific channel 
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user: return
if message.guild.id == 551544391395835914:
print("we are in memes")
if not message.attachments: await message.delete()
nah, you have to check by channel id, not guild id ofc
actually both to be perfect
so first if message.guild.id == <your guild id>
then
if message.channel.id == <memes chanel in that guild>:
if message.guild.id == 431065910040854539 and message.channel.id == 551544391395835914:
if not message.attachments: await message.delete()
I wonder if there's a way to delete even when they write a message as a photo description 
yup, should be fine
ever used commands? since the "ping" is kind of strange
ah no, don't worry about the content of the photo xD
well they didnt complain so i believe they knew it should be awaited either from documentation or just the fact that its an api call, but i guess that assumption doesnt apply to everyone
I meant, deleting a message in any case that there's a text
so if people send a photo/gif with a text in it
it gets deleted
write a msg as a photo description? you mean a link?
I mean like this
it's a photo with a message on top of it
help me please
I don't see any image
quite self explanatory
looks like you're following some kind of yt tutorial or copy pasting text
doiasodiasiodan
this time, I do
no
yeah it was an image of discord's background lOl
the idea is "delete any message that has text in it"
doesn't matter if it has photos as well
also I will have to find a way to see how to not remove gifs, cause for now they are removed
This line is on its own
so only keep images and gifs?
yes sir
well, seems like you didn't install the "readline" module then, whatever that is
So what's wrong with checking the attachments length?
I can't install it, I can only find .gz files even though I am on Windows
you mean in this way? if not message.attachments: await message.delete()?
what even is that and why do you need it?
that's fine... what're you worried about?
!pypi readline
first line in that lib "this is deprecated" lol
gifs are removed as well 
cause they are counted as text
if a person writes a text as an "attachment" to a photo [like the message I'm replying to] it doesn't get deleted
!pip gnureadline
seems like what you're trying to install is very outdated / unnecessary
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Il manque un argument.")
elif isinstance(error, commands.MissingPermissions):
await ctx.send("Vous n'avez pas les permissions pour effectuer cette commande.")```
also add: else: print(error)
its better to raise it ngl, the traceback is a lot more helpful
I agree
It does not put a blow that the person does not have the permission
do as said and the error will smile back at you
any ideas for a discord bot?
Yes
wsp
Make a bot which gives more bot ideas
Indeed
make a bot which returns Hunter neural network, so then you can ask ideas to it
because conditions aren't met (?)
what do you want the bot to delete though
i have this line of code
await message.channel.send ('1000') using discord.py
and i want to make it count down to 0 without using 1000 lines. pls help :)
use a loop
if 'jd' in message.content:
try it like this for now, since this is how I did it in my codes xd
Check better bro, it doesn't xD
Break keyword
yooo, can you help me now
try it since you mentioned to delete every word with jd in it xd
Oh hold up nvm
!e
lst_1 = ["jd"]
str_1 = "jd ab cd ef cg"
for i in lst_1:
print(True if lst_1 in str_1 else False)
wtf?
oh my bad
why not iterate
!e
lst_1 = ["jd"]
str_1 = "jd ab cd ef cg"
for i in lst_1:
print(True if i in str_1 else False)
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
True
oh wait nvm
See?
F
what tf for do you need a list with one item tho
a "Just in case Ill be adding something else" thingy π
Understandable
whats jd?
yeah i know i got rate limit, but why, when i literally send one message per hour?
well they have changed a lot of thinks in the last 3 months (don't worry probably no one here readed the new terms of use yet too) so you should check them and maybe you will find something
Because you're using replit
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ok thanks
anyone know why it sent me this everytime i try to send an image to the discord bot and let it edit the image using pillow?
https://paste.pythondiscord.com/imiduforon someone help trying to split image into 100 vertical sections and save each section as separate image but image saved at end is same image as inputted
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
ok
Such file doesn't exist
which one?
how to make a welcome command in discord.py??
when i try running the code on my friend'slaptop it worked
I think it's clearly visible
Of course because his files are named differently
try uploading the image to discord and copy link and put it into your code
That's why referencing external files is bad
db2.update_one({ "guild_id": guild.id }, { "$set": { "link": guild.vanity_invite()}})
why link is not updating here
vanity_invite is a property
Listen for on_member_join
it's not a callable object
then what should i use
!d discord.on_member_join
i tried
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Show the code
@bot.event
async def on_member_join(member, guild):
embed= nextcord.Embed(Title= "Welcome!", description=f"**Hello {member.mention}!**\nWelcome to **{guild.name}**!")
embed.set_image(url="https://tenor.com/view/no-way-home-spider-man-no-way-home-tobey-maguire-spider-man-portal-gif-25114767")
await welcome.send(embed=embed)
on_member_join only takes one parameter
sedd
what part of the files that are named differently
@cosmic agate please read this
hey how do i define guild's vanity invite there?
i only gave 2
I mean one
oh ok
- It doesn't take guild arg
- Where's
welcomedefined?
integrated like general
@whole dust just copy the file to project root and change the path to relative one
What
its integrated
Wdym by integrated
idk
but it should be a discord welcome channel
for example there are message
how do i show vanity invite code in my server info embed
messages like, welcome (user), we hope you brought pizza
What's your python knowledge level
about me
?
check my about me
Understandable
hmm i suppose you were in the same situation
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
everyone tells me that XD
Then do that
For now I can give you sample code
await message.guild.get_channel(welcome_channel_id).send(...)```
Replace the `welcome_channel_id` with your welcome channel id
hey pls help me how do i show guild's vanity code
!d discord.Guild.vanity_url_code
The guildβs vanity url code, if any
New in version 2.0.
How do, I run this bot, from github?
for i in list:
await message.channel.send(i)
await asyncio.sleep(.5)```
how would I make this send in the reverse order the table is in like from end to start
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
cluster = MongoClient("")
database = cluster["discord"]
collection = database["warn-database"]
class Warnings(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(name='warnings',aliases=["warns"])
@commands.has_permissions(manage_messages=True)
async def warnings(self, ctx, user:discord.Member=None):
id= user.id
if collection.count_documents({"memberid":id}) == 0:
collection.insert_one({"memberid":id,"warns": 0})
elif user==None:
return await ctx.send("Please mention a user!")
warn_count = collection.find_one({"memberid":id})
count = warn_count["warns"]
new_count = count + 0
collection.update_one({"memberid":id},{"$set":{"warns": new_count}})
await ctx.send(f"{user.mention} has **{new_count}** warnings!")
def setup(client):
client.add_cog(Warnings(client))
``` Not sure why it says this.
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
cluster = MongoClient("y")
database = cluster["discord"]
collection = database["warn-database"]
class Warn(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(manage_messages=True)
async def warn(self, ctx, user:discord.Member=None, *, reason=None):
id= user.id
if collection.count_documents({"memberid":id}) == 0:
collection.insert_one({"memberid":id,"warns": 0})
if reason==None:
return await ctx.send("Please mention a reason")
elif user==None:
return await ctx.send("Please mention a user!")
warn_count = collection.find_one({"memberid":id})
count = warn_count["warns"]
new_count = count + 1
collection.update_one({"memberid":id},{"$set":{"warns": new_count}})
await ctx.send(f"Warned {user.mention} for **{reason}** in **{ctx.guild}** | They now have **{new_count}** warning(s)!")
# @commands.Cog.listener()
# async def on_command_error(*args):
# print(args)
def setup(client):
client.add_cog(Warn(client))
``` It's not in my warn command either
oh i forgot
use the reverse func
for i in reverse(list)
oh alr thnx
Ψ @junior verge
Do in cmd
Anyone?
It's saying undefined "reverse"
pip3 <command>
How is this possible? When I don't have any aliases or other commands called that
!paste
Check warn https://paste.pythondiscord.com/odejekasob
Warn code: https://paste.pythondiscord.com/ayevosurat
maybe change the "warning" to something else such as alert. if you read the error it states it already exists
warnings is like checkwarns
Alright does someone know a lot about blockchain bots
is it discord related?
Yes
I have a bot running which is exploring the blocks on a token. I want to receive a messenge about bigger buys into a token. If someone buys 20 bnb worth of this token I want to receive a messenge in a server
import discord
from discord.ext import commands
from datetime import datetime
class Help(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def help(self, ctx):
embed=discord.Embed(title=f'Help Menu', timestamp=datetime.datetime.utcnow())
for command in self.client.walk_commands():
description = command.description
if not description or description is None or description == "":
description='No description Provided'
embed.add_field(name=f"`.{command.name}{command.signature if command.signature is not None else ''}`", value=description)
await ctx.send(embed=embed)
def setup(client):
client.add_cog(Help(client))
``` Is anything wrong with this command?
Can bs4 getText() from a tag with multiple classes , its only 1 tag but it has alot of classes
Ok sry to put it here
old account moment
I did exactly the same thing you asked me and it didn't work
it's outside of the cog
you're not subclassing the help command
you used an unnecessary f-string
if not description
is the same as
if description is None
you named your bot client
you could have made a cool one liner for the description π’
the field doesn't get added if description isn't None
you've got indentation problems
File "C:\Users\Mathis\PycharmProjects\FlashBotRebooted\cogs\normal\random-normal.py", line 32, in setup
await cursor.execute('CREATE TABLE IF NOT EXISTS users (guildId INTEGER , userId INTEGER , ratingStars INTEGER')
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.OperationalError: incomplete input
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Mathis\PycharmProjects\FlashBotRebooted\bot.py", line 132, in on_command_error
raise error
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: incomplete input
I have this error
@commands.command(
name="setup",
description="Setup the review system.",
)
async def setup(self, ctx: Context):
if ctx.message.author == ctx.message.guild.owner:
await ctx.send("Hi!")
async with aiosqlite.connect("ratings.db") as db:
async with db.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS users (guildId INTEGER , userId INTEGER , ratingStars INTEGER')
await db.commit()
await ctx.send("Hi!")
else:
embed = disnake.Embed(
title="Error!",
description="You are not the owner of the server!",
color=0xffffff
)
await ctx.send(embed=embed)
This is my code
ohh
indeed
thats so stupid
btw connecting to your database each time in a command can cause some issues
Just create a bot variable with your connection
Just passing on the information I was told π€·ββοΈ
Seems half baked. I mean it can because you could possibly have multiple unclosed connections in the connection pool. But you know if you close them every time you're finished with them, it should be fine.
Hello
π
Print("hello")
also, this command for some reason makes this error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\Mathis\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Mathis\PycharmProjects\FlashBotRebooted\bot.py", line 132, in on_command_error
raise error
disnake.ext.commands.errors.CommandNotFound: Command "test" is not found
@commands.command(
name="Test",
description="testing",
)
async def test(self, ctx: Context, member: disnake.Member):
async with aiosqlite.connect("ratings.db") as db:
async with db.cursor() as cursor:
for guild_id in ("users", "guildId"):
user_id = member.id
guild_id = ctx.message.guild.id
cursor.execute("SELECT rowid FROM components WHERE name = ?", (guild_id,))
data = cursor.fetchall()
if len(data) == 0:
print("No object found")
else:
print('Component %s found with rowids %s'%(guild_id,','.join(map(str, next(zip(*data))))))
await db.commit()
indentation looks off
?
Ty
Just a small nitpick, when you're printing the things why are you using placeholders
Why not just use f-strings
its just for a short test
Nah
i see
its just for a test
but i wonder why it says the command doesnt exist
the first command is in the same cog and works
show the whole cog
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
my_var = "True; DROP TABLE my_table"
connection().cursor().execute(f"INSERT INTO my_table VALUES({myvar})")
:lenny:
good point thx
Case matters unless you set case_insensitive to True in bot constructor
Also what are you even trying to iterate here
for guild_id in ("users", "guildId"):
...```
It will make two iterations, in first guild_id will be "users" and in second - "guildId"
You're welcome
im confused, but i dont question it
I am trying so it searches if the guild_id is in the row guildId
guys i want to let the bot use the file.txt and read it that the user sent thx
Isn't it the same thing lol
ok yeah
And which of these steps you are having issues with?
obtain message -> obtain file -> convert file -> read file
wdym on convert file
Put it to readable form
Can you show what code you have at this moment
def check(m):
return m.author == ctx.author and m.channel == ctx.channel and bool(m.attachments[0].filename.endswith('.txt'))
code = await bot.wait_for('message',check=check)
await code.delete()
code = code.content
await ctx.send(code)
with open(code,'r') as f:
code = f.read()
i am not very sure what is going on here
bot is waiting for txt file
class discord.File(fp, filename=None, *, spoiler=False, description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
just so you know this will raise an error if the message doesnt contain an attachment
what are you actually trying to do?
i want the bot to read the txt file that i give him
await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") object.
New in version 1.1.
message u mean m on my case right ? or what
def check(m):
return m.author == ctx.author and m.channel == ctx.channel and bool(m.attachments[0].filename.endswith('.txt'))
code = await bot.wait_for('message',check=check)
await code.delete()
code = code.content
await ctx.send(code)
with open(code,'r') as f:
code = f.read()
i mean code
owww
hi
@client.command()
async def info(ctx):
await register(ctx.author)
users= await get_date()
donated= users[str(user.id)]["donated"]
donations= discord.embed(title="Your Donations till now are")
donations.add_field(name="Amount", value= donated)
async def register(user):
users= await get_date()
if str(user.id) in users:
return False
else:
users[str(user.id)]["donated"] = 0
with open("database.json","w") as f:
json.dump(users, f)
return True
async def get_date():
with open("database.json","r") as f:
users= json.load(f)
``` error is that ```user``` is not defined
your check is fine apart from it raising error
It is not defined lol
Info command
should I define it again in the info command?
yup
the user id that will use this command
donated = users[str(ctx.author.id)]["donated"]```
Perhaps this is what you need
def check(m):
return m.author == ctx.author and m.channel == ctx.channel and bool(m.attachments[0].filename.endswith('.txt'))
code = await bot.wait_for('message',check=check)
await code.delete()
code = code.content
f = await code.attachments[0].read()
await ctx.send(f)
```som like this ?
f = await code.attachments[0].read()
AttributeError: 'str' object has no attribute 'attachments'
thank you
content is str, not message.
I want bot features code anyone?
literally just go through the thousands of python discord bots there are on github
Can you give me pls?
https://github.com/caedenph/jesterbot | definitely not self promo
follow me
Ok
Why do I receive this error when I try enable intents in my bot? (hosted on pebblehost)
14.03 17:13:20 [Bot] Traceback (most recent call last):
14.03 17:13:20 [Bot] File "/run.py", line 9, in <module>
14.03 17:13:20 [Bot] intents.message_content = True
14.03 17:13:20 [Bot] AttributeError: 'Intents' object has no attribute 'message_content'
how do I set a custom bot status in interactions.py?
how are you enabling the intents? || show code ||
from discord import Intents
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix = '.', intents=intents)
message content is privileged already?
It is supposed to be since april or smth
yesh april 31
why not just use discord.Intents.all() ?
because its not F.U.N.
what can backfire?
Oh that's may
I didn't know that exists
same thing uhh
!d discord.Intents
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
New in version 1.5...
!d discord.Intents.all
classmethod all()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents "discord.Intents") with everything enabled.
ur not fun nvr been and esp with ur emojis
oh ok
sometimes slower hosts cant handle all the events so limited intents speeds it up
what'd I even do to you
ah thats fair enough if no need then its a waste tbh
nothing perosnally just been annoyed u say nothing n just post emojis cause u have nitro
when i know u can code n help
(no hard feelings tho)
@slate swan what version of lib are you using
Python bot' automatic github code fetching from link is pretty nice
it shows a group a streamers that are live and shows in status how many of db are live atm of how many is in db
like 6 / 126 is now live.
latest
Print discord.__version__
ur not fun nvr been and esp with ur emojis
oh, 'no hard feelings tho' xD
whats yours?
Well this is my requirements.txt
discord
requests
random
time
os
json
no hard feelings over than that part... i dont hate her...
Seems like you are using latest stable
Pretty sure Intents.message_content is only available in alpha
are there any features you wish discord.py implemented?
Builtin time converter π
wdym by that
VersionInfo(major=1, minor=7, micro=3, releaselevel='final', serial=0)
Convert 5h2m to timedelta for example
Yeah this is latest stable
You need alpha version to use that intent
Check pins for instructions of how to install
It works but message_content doesn't exist in 1.7 so technically it is not enabled
I think I have done something horrible
But yeah by the time the intent becomes privileged the stable release will have that implemented so doesn't really matter
π me noob
true g
import discord
from discord.ext import commands
import json
import os
TOKEN = 'token hidden'
PREFIX = ['.cl ', '.clan ', 'kyn', 'Kyn']
INTENTS = discord.Intents.default()
client = commands.Bot(command_prefix=PREFIX)
@client.event
async def on_ready():
print(f'Logged in as: {client.user.name}')
print(f'With ID: {client.user.id}')
@client.command()
async def info(ctx):
await register(ctx.author)
users= await get_date()
user= ctx.author
donate_amt= users[str(user.id)]["donated"]
donated = users[str(ctx.author.id)]["donated"]
donations= discord.embed(title="Your Donations till now are", color=discord.Color.red)
donations.add_field(name="Amount", value= donated)
await ctx.send(donated)
async def register(user):
users= await get_date()
if str(user.id) in users:
return False
else:
users[str(user.id)]["donated"] = 0
with open("database.json","w") as f:
json.dump(users, f)
return True
async def get_date():
with open("database.json","r") as f:
users= json.load(f)
return users
@client.command()
async def donate(ctx, don):
await register(ctx.author)
users= await get_date()
user= ctx.author
saved= don
embed= discord.embed(title=f"{user.name} has donated")
embed.add_field(name= f"Donations amount: {don}")
users[str(user.id)]["donated"]+=don
if don >1000000 or don==1000000:
await ctx.send(f'lmao why are you so rich my friend, you have successfully donated {don}!')
else:
await ctx.send(f'You have successfully donated {don}!')
client.run(TOKEN)```
error:
Ignoring exception in command donate:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Startklar\Desktop\Oni clan\main.py", line 48, in donate
await register(ctx.author)
File "c:\Users\Startklar\Desktop\Oni clan\main.py", line 36, in register
users[str(user.id)]["donated"] = 0
KeyError: '811190019528196156'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\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: KeyError: '811190019528196156'
database.json cursed
lmfao
what do you mean?
there isnt any key of that kind in the data
π json uwu db
users[str(user.id)] = {"donated": 0}```
why?
I should paste this instead of all others?
This code executes in case user.id is not in users
oh
error π’ :
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Startklar\Desktop\Oni clan\main.py", line 54, in donate
users[str(user.id)]["donated"]+=don
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\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: TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Hi
Pretty simple
import discord
from discord.ext import commands
import json
import os
TOKEN = ''
PREFIX = ['.cl ', '.clan ', 'kyn ', 'Kyn ']
INTENTS = discord.Intents.default()
client = commands.Bot(command_prefix=PREFIX)
@client.event
async def on_ready():
print(f'Logged in as: {client.user.name}')
print(f'With ID: {client.user.id}')
@client.command()
async def info(ctx):
await register(ctx.author)
users= await get_date()
user= ctx.author
donate_amt= users[str(user.id)]["donated"]
donated = users[str(ctx.author.id)]["donated"]
donations= discord.Embed(title="Your Donations till now are", color=discord.Color.red)
donations.add_field(name="Amount", value= donated)
await ctx.send(donated)
async def register(user):
users= await get_date()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {"donated": 0}
with open("database.json","w") as f:
json.dump(users, f)
return True
async def get_date():
with open("database.json","r") as f:
users= json.load(f)
return users
@client.command()
async def donate(ctx, don):
await register(ctx.author)
users= await get_date()
user= ctx.author
saved= don
embed= discord.Embed(title=f"{user.name} has donated")
embed.add_field(name="Donations amount: ", value=don)
users[str(user.id)]["donated"]+=don
if don >1000000 or don==1000000:
await ctx.send(f'lmao why are you so rich my friend, you have successfully donated {don}!')
else:
await ctx.send(f'You have successfully donated {don}!')
client.run(TOKEN)```
I wanna create my private discord bot. Please guide me.
What do you need specifically?
wait was I supposed to do @client.command with parentheses?
ig that's why it didn't work, don't remember tho lol
I want to highlight my pasted code.
!code this?
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.
In my personal chat
can you explain
print("yo")```like this?
print("hello world")
Will it work in personal chat too?
what's personal chat? and what are you talking about... syntax highlighting on discord?
personal chat
do you mean dms?
ig so
it's the exact same as on a server
lol
?
Can't use += on a string and integer
class Counter(discord.ui.View):
@discord.ui.button(label='Close Ticket', style=discord.ButtonStyle.red)
async def count(self, ctx, button: discord.ui.Button, interaction: discord.Interaction):
with open('data.json') as f:
data = json.load(f)
if ctx.channel.id in data["ticket-channel-ids"]:
channel_id = ctx.channel.id
def check(message):
return message.author == ctx.author and message.channel == ctx.channel and message.content.lower() == "close"
try:
em = discord.Embed(title="", description="Are you sure you want to close this ticket? Reply with `close` if you are sure.", color=0x000080)
await interaction.response.send_message(embed=em)
await bot.wait_for('message', check=check, timeout=60)
await ctx.channel.delete()
with open("data.json") as f:
data = json.load(f)
ticket_number = int(data["ticket-counter"])
channel = bot.get_channel(793569113708036106)
color = discord.Color.red()
em = discord.Embed(color=color, description=(f"{ctx.message.author} closed a ticket\n **Ticket #**\n {ticket_number}"))
await interaction.response.send_message(embed=em)
index = data["ticket-channel-ids"].index(channel_id)
del data["ticket-channel-ids"][index]
with open('data.json', 'w') as f:
json.dump(data, f)
except asyncio.TimeoutError:
em = discord.Embed(title="", description="You have run out of time to close this ticket. Please run the command again.", color=0x000080)
Ignoring exception in view <Counter timeout=180.0 children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Close Ticket' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 373, in _scheduled_task
await item.callback(interaction)
TypeError: count() missing 1 required positional argument: 'interaction'```
πΏ
bruh
I heard discord .py is back?
yes the development is continued
s = s + str(i)
convert the integer to string
thank you
Convert the integer to a string or the string to a integer
my bad itβs reversed
You have to re-cast tho
bring the json db
list(reversed(listobj))
Can anyone tell me how to configure a bot to delete messages in a discord channel after a certain time of sending?
you can use asyncio.sleep
send(..., delete_after=5)
or that ye
Hmmm, i'll try it, thanks
Wait, but what I mean is deleting other people's messages, not the bot itself
Make a task
@commands.command(
name="test",
description="Setup the review system.",
)
async def test(self, ctx: Context, member: disnake.Member, *, rating : int = 0):
async with aiosqlite.connect("ratings.db") as db:
async with db.cursor() as cursor:
await cursor.execute("SELECT userId FROM users WHERE guildId = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if data:
await cursor.execute("UPDATE users SET userId = ? WHERE guild = ?", (member.id, ctx.guild.id))
else:
await cursor.execute("INSERT INTO users (guildId, userId, ratingStars) VALUES (?, ?, ?)", (ctx.guild.id, member.id, rating))
await db.commit()
This is my command, but nothing shows up in the database
also no errors
message.edit(delete_after=5)
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function no-longer raises `InvalidArgument` instead raising [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)").
Thank you!
Only with delete_after you can
Try it yourself
However if you provide any other params you are gonna get http exception
It worked perfectly as I wanted. Thank you to everyone who helped.
hi its me again
import discord
from discord.ext import commands
from datetime import datetime
class Help(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def help(self, ctx):
embed=discord.Embed(title=f'Help Menu', timestamp=datetime.datetime.utcnow())
for command in self.client.walk_commands():
description = command.description
if not description or description is None or description == "":
description = 'No description Provided'
embed.add_field(name=f"`.{command.name}{command.signature if command.signature is not None else ''}`", value=description)
await ctx.send(embed=embed)
def setup(client):
client.add_cog(Help(client))
``` How do I get this fixed?
Ignoring exception in command info:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Startklar\Desktop\Oni clan\main.py", line 24, in info
donated = users[int(ctx.author.id)]["donated"]
KeyError: 811190019528196156
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\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: KeyError: 811190019528196156```
this is the error and this is the code
```py
import discord
from discord.ext import commands
import json
import os
TOKEN = 'hidden token'
PREFIX = ['.cl ', '.clan ', 'kyn ', 'Kyn ']
INTENTS = discord.Intents.default()
client = commands.Bot(command_prefix=PREFIX)
@client.event
async def on_ready():
print(f'Logged in as: {client.user.name}')
print(f'With ID: {client.user.id}')
@client.command()
async def info(ctx):
await register(ctx.author)
users= await get_date()
user= ctx.author
donate_amt= users[str(user.id)]["donated"]
donated = users[int(ctx.author.id)]["donated"]
donations= discord.Embed(title="Your Donations till now are", color=discord.Color.red)
donations.add_field(name="Amount", value= donated)
await ctx.send(donated)
async def register(user):
users= await get_date()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {"donated": 0}
with open("database.json","w") as f:
json.dump(users, f)
return True
async def get_date():
with open("database.json","r") as f:
users= json.load(f)
return users
@client.command()
async def donate(ctx, *don):
await register(ctx.author)
users= await get_date()
user= ctx.author
saved= str(don)
embed= discord.Embed(title=f"{user.name} has donated")
embed.add_field(name="Donations amount: ", value=don)
users[int(user.id)]["donated"]+=don
if don >1000000 or don==1000000:
await ctx.send(f'lmao why are you so rich my friend, you have successfully donated {don}!')
else:
await ctx.send(f'You have successfully donated {don}!')
client.run(TOKEN)```
Good answer
error?
lemme try
ok
Will discord bots using discord.py stop working after April 30th?
no
the creator is working on it again
why would it stop working
it was going to stop cuz of the slash commands thing
it better not stop lol i only know how to use python
o
no such key
well the error says it all
ye just a tab
what do you mean, sorry I am new
if theyre using dpys old ver yeah
!e print({"key": "value"}["secondkey"])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | KeyError: 'secondkey'
What is the old dpy version?
1.7.3
For some reason, after ive edited my code and changed the prefix, the bot just ignores the changes like i never made them
The prefix.
did you restarted your bot?
did u close the terminal and save it and then run the code again
Yeah, the bot is hosted on Heroku Github. Does it have anything to do with that?
yes its hosting the old code of your bot
But github has the new code?
you need to update it with your current code so it will run your bot with the new changes
My github has my new code.
seems like its still running the old code
hey i just try whatever man
thats not like python works lol
it works for me
what is the new dpy version?
Keyword:
lol
thats nice but in this situation it wouldnt matter
main
chill lol
Restarting heroku dynos and re-deploying
Is there maybe a VS Code plugin where i can edit my code from Github live or update from VS?
thanks π
thats weird its still running for some what reason
Add __pycache__ to .gitignore btw
why exactly?
what?
The token um
isnt pycache for like caching logs or something related to runtime
π
reset it
As you can see, im a dumbass.
It is not a code file and should not be on version control
please dont say that to yourself youre clearly not
what is it for then
Itβs bytecode cache
Itβs generated at compile time
ah so it caches bytes
yeah ik that
for what reason exactly? to make it easier to compile?
And that's supposed to help me?
mhm makes sense
I don't know anything about Github, I just followed a tutorial.
https://stackoverflow.com/questions/16869024/what-is-pycache normal explanation I'd say
Ok, so how do I implement this?
Implement pycache??????
add it
.
thatβs what you meant
You donβt really need to by any circumstances.
But it prevents clutter ig
Do pip install discord.py in integrated terminal
anyone knowp why this happens when i run?
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1007, in new
self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry'
exit status 1
Traceback (most recent call last):
File "/opt/virtualenvs/python3/bin/pip", line 5, in <module>
from pip._internal.cli.main import main
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pip/__init__.py", line 1, in <module>
from typing import List, Optional
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1359, in <module>
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1007, in __new__
self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry'
thats what ahppened when i pip installed discord.py
pip uninstall typing
same thing happens
run pip uninstall python
π give me the output of pip list
raceback (most recent call last):
File "/opt/virtualenvs/python3/bin/pip", line 5, in <module>
from pip._internal.cli.main import main
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pip/__init__.py", line 1, in <module>
from typing import List, Optional
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1359, in <module>
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1007, in __new__
self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry'
is something wrong in requirements.txt?
@manic wing btw what's wrong with pip install discord
Traceback (most recent call last):
File "/opt/virtualenvs/python3/bin/pip", line 5, in <module>
from pip._internal.cli.main import main
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pip/__init__.py", line 1, in <module>
from typing import List, Optional
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1359, in <module>
class Callable(extra=collections_abc.Callable, metaclass=CallableMeta):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/typing.py", line 1007, in __new__
self._abc_registry = extra._abc_registry
AttributeError: type object 'Callable' has no attribute '_abc_registry'
its a mirror package
!pypi discord
A mirror package for discord.py. Please install that instead.
So basically it redirects to discord.py right?
sort of but it gets updated less often and isnβt the real deal
Ok
do yk whats wrong?
i do; i told you twice but thereβs a point where i stop
The name of the command.
ctx.command.aliases
W
returns a list of str
or you can use str.join(list)
oki
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
!e x = ["a", "b", "c"]
print(",".join(x))
@manic wing :white_check_mark: Your eval job has completed with return code 0.
a,b,c
str.join(map(str, iterable)) for non-strings
i like tha format
Hello, im trying to make the bot get a certain message, it can get messages sent by a user, but not by itself when the message is a embed. How could i get it?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
msg = await ctx.fetch_message(message)
I donβt want to make another param just for the channel if I were to use partial message either
what can i do to get the author name when my button is presed py color = discord.Color.red() em = discord.Embed(color=color, description=(f" closed a ticket\n **Ticket #**\n {ticket_number}")) await channel.send(embed=em)
inter.author probably
It is
so (f"{inter.author} closed a ticket\n **Ticket #**\n {ticket_number}")
try it ig
I canβt buy anything
havent done much with buttons
send the code, screenshots dont load
Ok
@client.command()
async def buy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That Object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy {amount} {item}")
return
await ctx.send(f"You just bought {amount} {item}")
nope duz not work
@client.command()
async def buy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That Object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy {amount} {item}")
return
await ctx.send(f"You just bought {amount} {item}")
Itβs inter.user
!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.
then ctx.fetch_message should be good
perhaps there's just no message with that id in that channel
hello, what is the pip install for the discord activities ?
@client.command()
async def buy(ctx,item,amount = 1):
await open_account(ctx.author)
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That Object isn't there!")
return
if res[1]==2:
await ctx.send(f"You don't have enough money in your wallet to buy {amount} {item}")
return
await ctx.send(f"You just bought {amount} {item}")
Not letting me buy anything
Update: the bot doesnt work at all. :/
hi
I am having this keyerror about 2 hrs ago
but I couldnt solve it
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Startklar\Desktop\Oni clan\main.py", line 22, in info
donations_amt= users[str(user.id)]["gold"]
KeyError: '811190019528196156'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\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: KeyError: '811190019528196156'```
import discord
from discord.ext import commands
import json
import os
TOKEN = 'token hidden'
PREFIX = ['.cl ', '.clan ', 'kyn ', 'Kyn ']
INTENTS = discord.Intents.default()
client = commands.Bot(command_prefix=PREFIX)
@client.event
async def on_ready():
print(f'Logged in as: {client.user.name}')
print(f'With ID: {client.user.id}')
@client.command()
async def info(ctx):
user= ctx.author
await open_account(ctx.author)
users= await get_bank_date()
donations_amt= users[str(user.id)]["gold"]
em= discord.Embed(title= f"{ctx.author.name}'s donatiosn amount ", color= discord.Color.red())
em.add_field(name="the amount you have donated: ", value= donations_amt)
await ctx.send (embed=em)
@client.command()
async def donate(ctx, **don):
await open_account(ctx.author)
users= await get_bank_date()
user= ctx.author
donated= don
await ctx.send (f"you have donated {donated} succesfully! ")
users[str(user.id)]["gold"] += donated
with open("database.json", "w") as f:
json.dump(users, f)
async def open_account(user):
users= await get_bank_date()
if str(user.id) in users:
return False
else:
users[str(user.id)]= {}
users[str(user.id)]["gold"] = 0
return
with open("database.json", "w") as f:
json.dump(users, f)
return True
async def get_bank_date():
with open("database.json", "r") as f:
users= json.load(f)
return users
client.run(TOKEN)```
Make sure that str(user.id) is a key within your dictionary when trying to donate. If the user ID is not in the dictionary, add it before referencing it as a key, which is why you're getting the KeyError
also, should I add them manualy?
So just make sure they open account before you donate to them essentially
thats what I was trying to do
like it should check if they have a account opened before or not
if yes then it should go to next
if not i t should create one for them
how i can make spolier at webhook from dhooks ?
I am trying to run this but it is not prompting on the server. In the code it says there is an inconsistency in this part, does anyone know what it could be?
Yeah
tysm<3
I've a problem
Seems like a linter issue thinking that w_channel is not one variable
I got the error :
SyntaxError: Non-UTF-8 code starting with '\xfe' in file C:\...\zoumoubot.py on line 2, but no encoding declared; see https://python.org/dev/peps/pep-0263/ for details
I tried to change the name but the error persists :/
And it should be a problem of encoding, but all the characters of my script are UTF-8 and I don't manage to run my bot
name it one word
Also, it has been working thirty minutes ago and I've made no major change
And it doesn't work whether I put "# -- coding: utf-8 --" or not
Guys there is something weird happening in my code for some time it the buttons work but suddenly it always says no module discord.ui found
I changed it to a single word name as well, but when I run the bot it is not sending the message on the discord channel. No error appears in the console, but it doesn't work either...
Yeah you need to be on 2.0.0
how can i update
pip install -U git+https://github.com/Rapptz/discord.py
just erros appear in console
whenever i type it and download it
it always put discord.py 1.7.3 for me
You forgot the egg.
?
Uninstall the current version of discord.py you got.
pip uninstall discord.py
And install the main repository branch.
pip install git+https://github.com/Rapptz/discord.py#egg=discord.py
ok
ERROR: Command errored out with exit status 1:
command: /home/runner/Tuition/venv/bin/python3 /tmp/pip-standalone-pip-xtbszjnk/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-jzks134z/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://package-proxy.replit.com/pypi/simple/ -- setuptools wheel
cwd: None
Complete output (1 lines):
/home/runner/Tuition/venv/bin/python3: can't find '__main__' module in '/tmp/pip-standalone-pip-xtbszjnk/__env_pip__.zip/pip'
----------------------------------------
WARNING: Discarding git+https://github.com/Rapptz/discord.py#egg=discord.py. Command errored out with exit status 1: /home/runner/Tuition/venv/bin/python3 /tmp/pip-standalone-pip-xtbszjnk/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-jzks134z/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://package-proxy.replit.com/pypi/simple/ -- setuptools wheel Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement discord-py (unavailable) (from versions: 0.1.0, 0.2.0, 0.2.1, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.7.0, 0.8.0, 0.9.0, 0.9.1, 0.9.2, 0.10.0, 0.11.0, 0.12.0, 0.13.0, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.16.7, 0.16.8, 0.16.9, 0.16.10, 0.16.11, 0.16.12, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3)
ERROR: No matching distribution found for discord-py (unavailable)
error it seems it can only get 1.7.3
I copied it from the official discord.py announcement
I looked for the error in my code but could not find it. It runs normally, but is not responding in discord. I already gave the necessary permissions to the bot in the room but it doesn't send the message in the welcome channel...
It will work
Clone the repo and run python3 -m pip install .
wdym
Get the TextChannel object, then send the message to it. Don't use client.send_message.
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
What do you mean?
are there any features you wish dpy/your fork implemented?
me?
anyone
all i want is discord.ui, before it was working perfectly but it suddenly gave the error
that no module called discord.ui
@outer parcel did u have an error when doing this?
the ui ext is only available in d.py 2.0, which isn't released on pypi yet
Clone the repo using git and run this command: python3 -m pip install .
you need to install it directly from the repository
To install the development version, do the following:
$ git clone https://github.com/Rapptz/discord.py $ cd discord.py $ python3 -m pip install -U .[voice]```
try this:
pip install -U git+https://github.com/Rapptz/discord.py
(In sheβll)
That way?
channel.send needs to be awaited
^
Oh, fact
idk why you removed await
I don't either
looks okay, I would look into using discord.ext.commands.Bot instead of discord.Client solely for additional built in support features.
Ok π
it looks like you're using repl, you might not be able to use d.py 2.0
also your print statements indicate that your are messaging the user and the channel, but your code only ever messages the channel. you may want to consider adding that function by way of member.send as discord.Member is a subclass of discord.abc.Messageable
You can still use d.py 2.0 on replit
2.0
also also, your original code suggested that you may be following an outdated tutorial. I would recommend trying to find one that was published within the last year or so because the library has not undergone major changes since then. (it is currently undergoing a lot of major breaking changes but none that have been officially released on pypi (or pip)
Regardless, it's best to stay off replit
Causes ratelimits due to 1 ip.
if you're using replit to circumvent the ratelimit that's against the terms of service
If you're getting ratelimited it's for a reason and you should respect that
i figure you might know this, but in my help command i have command.signature, for slash commands would it be like slash_command.signature?
hm, i figure it might be similar
Not sure about that. Haven't used the other forks so I can't be the judge of that
What about with D.py?
p sure yea
If you have any problems with slash commands on d.py let me know and I can try to help
kk
Okay so I updated to latest d.py a about 10 mins ago and now I can't start my bot, getting this errorpy File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\aiohttp\helpers.py", line 284, in get_running_loop if not loop.is_running(): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 111, 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') File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 111, 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') Exception ignored in: <function ClientSession.__del__ at 0x000001D938C3C820> Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\aiohttp\client.py", line 326, in __del__ if not self.closed: File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\aiohttp\client.py", line 963, in closed return self._connector is None or self._connector.closed AttributeError: 'ClientSession' object has no attribute '_connector'which I assume to be related to the asycio changes. This is my full code, I felt sharing the repo made more sense than lots of code blocks or online sites https://github.com/SnowyJaguar1034/Zupie
Check line 111
I havenβt checked ur code and I can already tell that it is because the loop or sumthing is out of an async function. (Idk if im right, im too lazy to check)
Can someone help me? This is my error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Games' object has no attribute 'random'
remove the self
random.choice
omg ty lol. i been trying to figure it out for a bit now and everyone i asked advice from said something wrong and ur the first one of like 5 people to actually be usefull lol
lol
they all said stuff like remove import random. idk why
that just a module so
If you're talking about cooldowns, slash commands don't have a native way to implement a cooldown, you'll have to do that yourself. Perhaps a database that stores the last time a user used a certain command
oh god 
If you're using postgresql you can store date/time: https://www.postgresql.org/docs/9.1/datatype-datetime.html
I want to make a command which sends random embed responses. I have searched it a lot but i didn't find anything
Ok, so import random, make a list of the embed names, make the embeds and then random.choice("list")
wait because it said something about str in the error
What's the error?
'str' object has no attribute 'to_dict'
Does it say a certain line
Me
Send the line
True
Itβs prob not needed
await ctx.send(embed=random.choice(mouse10))
Show the mouse10 list?
Ok wait
u should make the random.choice a variable (just a suggestion)
Because I think it's taking the random choice as 'value' rather than value
mouse10=['zero', 'sharkoon']
Possibly, I haven't touched random too much
how can i make it so that my bot is always running, even when im offline and closed the tab? i tried connecting it to a flask web server and then used an uptimerobot monitor to ping the bot every 5 minutes, it works but sometimes the bot just goes offline still, and i have no clue how
you can't do something better
Ok u needa remove the single quotes and then make a embed out of those items in the iterable
Before the list
that's uptimerobot
i have the embeds
Itβs bound to go off at some time use a database
Remove the quotes if zero or sharktoon is connected to a embed
It says undefined name
Wait
how
I think it's ok
Because thatβs how it is, even if u have a $1000 uptime robot of some sort or if u talking about database use SQLITE
Bruh
It worked but it always sends the one embed
Send replit
Ok wait
Or just the code
in dms or
^^ you can also do it locally
U can send it here
okay i send it here
It's at pccmds.py
no, like how would i go about doing a database
never done it before
YouTube
Learn SQL
how would a database make his bot be on for 24/7?
That's what I'm thinking
seeing a lot of database talk here - #databases
i've been literally thinking what is this conversation for the past 5 minutes
you cant host a bot in a db bruh

if you think you can make your bot be on for 24/7 because of what he said
you can't
a database stores info for your bot, infractions, messages, bans
Anybody got any suggestions/tips on when/where i should use @before_invoke() and @after_invoke()? I'm not sure when I should use them before I'm not sure if I need to use them. I se d.py's docs say they are useful for closing db connections when they are no longer needed but I'm not sure where else they can be useful
a hosting platform is what makes your bot online
!d disnake.ext.commands.Bot.before_invoke
@before_invoke```
A decorator that registers a coroutine as a pre-invoke hook.
This is for text commands only, and doesnβt apply to application commands.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a [`Context`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Context "disnake.ext.commands.Context").
Note
The [`before_invoke()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.before_invoke "disnake.ext.commands.Bot.before_invoke") and [`after_invoke()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.after_invoke "disnake.ext.commands.Bot.after_invoke") hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.
no a db can store any data
lol ik Iβm assuming he wants data to be saved so I recommended a database
!d disnake.ext.commands.Bot.after_invoke
@after_invoke```
A decorator that registers a coroutine as a post-invoke hook.
This is for text commands only, and doesnβt apply to application commands.
A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a [`Context`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Context "disnake.ext.commands.Context").
Note
Similar to [`before_invoke()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.before_invoke "disnake.ext.commands.Bot.before_invoke"), this is not called unless checks and argument parsing procedures succeed. This hook is, however, **always** called regardless of the internal command callback raising an error (i.e. [`CommandInvokeError`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CommandInvokeError "disnake.ext.commands.CommandInvokeError")). This makes it ideal for clean-up scenarios.
im giving examples
Yes, those parts of the code were really aimed at sending direct messages. That's because I got it from another code, but what I want to do is just post it to the channel. Unfortunately it didn't work yet, I didn't find out why π¦
why did you assume that
Cuz I wanted to
well, if you want data to be temporary like sniped messages or the sort, dtbases aren't necessary, you can just store it in a dict
so you assumed it randomly
Yeah
πΏ
Yeah
no
another question, is there a fancier way of making commands than if message.content.startswith(command) that most people use?
yes lol
yes dicts reset their value on a restart hence why people use dbs
show me your ways please
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
this represents a bot
the heck
Is there an error in the code that is preventing it from working correctly? My discord bot isn't sending messages, but the console doesn't show any errors. I already checked the bot permissions and everything is fine.
makes sense
oops
does this look fine to u @slate swan ```py
per = 0
def is_premium():
async def check(ctx):
array = cl.find_one({"_id" : 849658396675276841})['list']
global per
if ctx.guild.id in array:
per = 1800
return per
else:
per = 3600
return per
return commands.check(predicate = check)
@client.command()
@is_premium()
@commands.cooldown(1, per, commands.BucketType.guild)
async def test(ctx):
await ctx.send("L")```
!d disnake.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
is that channel id a text channel?
Yep
maybe instead of sending a message in a channel, do await member.send('Welcome!')
since if "Welcome" is just spammed in that channel by a bot
The first def is working well
it wouldn't look very nice
You are right. Actually I just put it in to test if the code is working.
yeah I've read that in the docs, but waht sort of setup/cleanup would you need to do for a command?
idk, i've never used it before
never had the need to
I would like to notify this room because only I can see. I plan to show the user who has logged in and who has logged out. I know there are some bots ready that have this functionality, but I would like to learn how to do it.
yeah i'm in the same boat, then again never haven't used it I don't know if maybe I should have used it and just didn't
you mean a like a staff chat?
Yep
use a bot, not a client
if file.endswith(".py"):
name = file[:-3]
bot.load_extension(f"cogs.{name}")```
Is their a new way to write this in v2.0.0a
I used client because I saw it in an example. But I saw others using bots instead of client. I will try to see how to do it correctly.
No, it's an integer
Hence "id"
Id can be for any type of channel whether text or voice and etc..
am i smart for this or dumb lmao ```py
def is_premium(ctx):
array = [864528215036002314]
print(ctx.guild.id)
if ctx.guild.id in array:
return True
else:
return False
@client.command()
@commands.cooldown(1, f'{3600 if is_premium is False else 1800}', commands.BucketType.guild)
async def test(ctx):
print(is_premium)
await ctx.send("d")```
anyone know how to add d.py 2.0 app_commands to my main.py file, my bot var has a command tree automatically registered so I don't need to declare one (in fact I get a warning if I try to declare a second) however I get a warning that tree is not defined when I try to dopy @tree.command() @app_commands.guilds(discord.Object(id=default_guild)) async def tree(interaction: discord.Interaction): await bot.tree.sync(guild=discord.Object(id=interaction.guild_id)) await interaction.response.send_message(f'Synced the tree.', ephemeral=True)and if I do @bot.tree.command I get another warning about making duplicate command tree's
pip install -U git+https://github.com/Rapptz/discord.py
yeah i have d.py installed and up to date
Oh
nice

you forgot allot of commas
Send the full traceback
i think u need to turn it to an int
the color has to be an int
for the color= field
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'int'>
π
Type hint it, don't assign it
no why?
Why not typehint it as discord.Colour? It calls the Colour converter which accepts hexcode & rgb
see why, see andy's messages 
you said it for no reason so shhh
I didnt?
lucky ou have andy to cover you
can anyone help me with starting my bot, since dpy updated there was a lot of breaking changes and i dont understand how the docs want me to start my bot since the exmaple they gave was never how i was doing it to begin with lol
here is how im currently doing it https://paste.pythondiscord.com/iqaromuwiv
these are the correct things according to the docs that i'm using and the requests link that i'm using. but yet it's giving me error that it isn't correct. can someone help me w this or?
https://tokyotokyotokyotokyo.tokyo/ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
docs: https://ipgeolocation.io/documentation/ip-geolocation-api.html
Use pastebin, its prompting to download the code
What do you mean?
It's the time_zone.name and asn lines that are giving the error
Otherwise the code works perfectly
this link - https://tokyotokyotokyotokyo.tokyo/β
use pastebin
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What is the purpose of this?
Seems kind of fishy
Working on a multi purpose bot
Yeah, wont help with that 
A multipurpose bot with IP geolocation features?
mhm, not all it has lol
Right, but that specific part is bordering on rule 5
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
yeah well it isn't breaking any laws or breaching terms
because it's getting access from online information
It's already public, which doesn't make it illegal
How are you getting access to someone's IP?
Who says I'm getting someone's ip?
through an argument
async def uwuip(ctx, ip=None)```
The API seems to need an IP to function
Yeah it does, but an ip can also be found online, which in that case, makes it public
For instance, google.com
If you ping google.com it'll give you an IP, which makes it public information, which doesn't break the law etc
Yes their DNS points to that record but I'm concerned about its uses with actual users
I think we should err on the side of safety and not assist you with this project. We cannot be 100% sure of the intentions behind this IP geolocation feature
just ping google.com in cmd
google.com's ip that it's letting you ping is 142.250.179.142
uhh the user inputs an argument uhh
async def uwuip(ctx, ip): pass```
Which is accessible to the public
that gets your IP ( from.which request was made ), not the user's
Yes we know, that's what their DNS records point to. I'm talking about the potential uses for actual users
π ash and her uwu things
Yeah well, even then if it's being used on users, it still won't give any other information out then the geolocation
So no harm done there

for instance if i take my proxy ip, it'll just give me general information
there's a reason why im not including alot of information in the codeblock
i'd rather use the api that im using rn because i've had a subscription to it for a while now
and i can put to use via this way
so thank you, but no thank you
why buy when you can get it for free
because i have $ to waste?
cool


