#discord-bots
1 messages Β· Page 692 of 1
why do I get an error when I try to send an ephemeral message using await ctx.channel.send("message", ephemeral=True)?
ephemeral only works for interactions and slash commands, not for normal message
does it not work for normal commands?
Can I not use gspread attributes when using gspread_asyncio?
not for normal message, it works for interactions and slash commands
I don't know, sorry
It's all good, I'm a bit confused as well
Can I use synch modules in discord bots?
got 1 more will send when i find ir
I think await message.channel.send(content=None, embed=embed) you don't need content=None
sure, but its gonna be blocking and gonna make your bot slow since dpy is async
maybe but thats not the problem
you received 404 response code which is invalid, well denied or smth
Yeah, it's what I assumed as well. But I'm struggling with gspread_asyncio since there's few documentation/tutorials about it
its probably a invalid subreddit
might be
@client.command()
async def report(ctx, user:discord.User, reason):
db = sqlite3.connect("main.db")
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
channel = get(result)
await channel.send(f"{user} has been reported for {reason}")
db.commit()
cursor.close()
error:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'send'
I printed the variable result and it gave me this: ('850356901232771085',)
and this is the table:
this is sqlite3
its a reddit api (praw)
don't use f-string with SQL
get the channel obj first
try handling the exception with try/except when making a request
my bot is on 31 servers taking pics from 20+ subreddits 24/7
I just started sqlite an hour ago xd
might just be a performance error
how exactly, Im so lost with sqlite3 xd
ctx.guild.text_channels, id=result try this in the get method
give a try to handling exception and see what happens
@client.command()
async def report(ctx, user:discord.User, reason):
db = sqlite3.connect("main.db")
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
channel = client.get_channel(int(result))
await channel.send(f"{user} has been reported for {reason}")
db.commit()
cursor.close()
maybe trying this?
where do I put the ctx.guild.text_channels
read my message
in the get method
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
try using this, for me it works. I use it in all my bots
spoonfeeder GG
and no, this aint gonna work because the variable result is = ('850356901232771085',)
he casted it though
xd, and I think I putted it in the wrong place
if it doesn't work just do .replace("('", "")
and .replace("')", "")
then convert to int
and it should work
why do you need to replace the ('?
I was planning to do that already cause Im so confused on the other method xd
@client.command()
async def report(ctx, user:discord.User, reason):
db = sqlite3.connect("main.db")
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
id = ctx.guild.text_channels(result)
await id.send(f"{user} has been reported for {reason}")
db.commit()
cursor.close()
and Bruh me
bruh.
i think this is worng
lemme write you a full example with the replace
don't spoonfeed...
did you even read my message? and do what filip said to convert it into an integer
Is there some kind of event that a bot can listen to messages that are sent as a reply to the bot's message?
!d discord.Message.reference
@client.command()
async def report(ctx, user:discord.User, reason):
db = sqlite3.connect("main.db")
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
res1 = result.replace("('", "")
res2 = result.replace("')", "")
channel = client.get_channel(int(res2))
await channel.send(f"{user} has been reported for {reason}")
db.commit()
cursor.close()
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
y?
what?
why is it bad?
sql injection risk
@boreal ravine try to put this, it removes the ('') and convert to int
it should work with ('ID') too
im not the one who asked for help
whats that?
why do you need to remove the ('?
Uhhh what
because if you don't remove it python can't convert it to an integer
U need to add a comma to make it a tuple
oh sorry
eevee looks fruity
I thought it was giving a tuple as output π (I usually end up getting it)
Wym
!e print(type((1,)))
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
<class 'tuple'>
U need to add a comma, as I said
lol just do `print(type(result)) to check it
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'replace'```
I don't have time to write that and test it
oh wait
result of quick google "SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database."
didnt work
Cool 
Β―\_(γ)_/Β―
nitro flex 
@client.command()
async def report(ctx, user:discord.User, reason):
db = sqlite3.connect("main.db")
cursor = db.cursor()
cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
result = ''.join(result)
channel = client.get_channel(int(result))
await channel.send(f"{user} has been reported for {reason}")
db.commit()
cursor.close()
but how tf can someone interfere with a db without accessing our code by us doing f-strings inside of a query
It's a bit hard to explain, the simple rule is to never use f string in SQL
As long as u dont use f strings for user input, u r fine
tbh that makes no sense?
U can use f strings for user IDs and stuff, but never use those for names or user inputs
it's bad usage
If I wanted to have a event that was timed but I could cancel any time I wanted how would I do that, would the best way is to have a global variable that is changed when I stop the event?
hm
You should use placeholders as they are the safe method, learning to use SQL in bad way (in this case f-string) is not good
didn't the error say it was a tuple? you can just index the tuple and do int(result[0])
why didn't you try tho
try what?
int(result[0])
Whatβs the error
from my database a similar output worked perfectly fine with this
I was just trying to get the best method to get it working π
And I think I maybe caused a bit of confusion
yeah you did the right thing
i proposed my solution, your is better
main thing is to get it working π
yeah, and in the better way!
π .
hello, inside cog using cog.listener can we track the voice part like if bot is not playing audio or something like that?
cog.listener is the same thing as @bot.event
i don't know if yes or not, but i think thaty is not an api event.
yeah but my music part is inside cog so..
you should you a while loop
hmm ok
when you start play, create a var named is_playing idk and assign it True
when you stop, assign it False
while is_playing:
i did this for my bot
eyyy problem solved
nice!
ok
How can I get all the message references from a certain message, if I have the message object of it?
what do you mean with references?
a reply, like I just did to your message
hey, how do i get the person that invited a member?
!d discord.MessageReference
class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)```
Represents a reference to a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.5.
Changed in version 1.6: This class can now be constructed by users.
@snow flare it should be what you are searching for
invite tracker?
ye kinda
sounds difficult to do
well, that is just a messagereference object
best of luck
i think discordutils has a thing for that

o alr
thanks
!pypi DiscordUtils
DiscordUtils is a very useful library made to be used with discord.py
i think you can get message id and content from it
!pypi securedb
UwU
yo nice lib @plain shadow
but i'm not sure, never used it
thanks! happy to hear that
omg already got 37 downloads
hm
Hey. How do I add emojis to guild?
I've figured out how to add an emoji existing in my pc (a jpeg file stored locally) to an guild but how do I add an emoji which is an url, without downloading it first?
!d discord.Guild.create_custom_emoji get the link content and upload it
i tried installing discord.py (py -3 -m pip install -U discord.py, straight from the docs) and it gives me a few warnings, but overall it doesn't throw errors, and then, when i try importing it (import discord), it's not resolved, and throws an error saying i dont have discord.py installed
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
I'm making commands from a JSON file. My file looks like this:json [ { "name": "hello", "output": "Hello!" }, { "name": "goodbye", "output": "Goodbye!" } ] I have figured out how to make new commands, but I don't know how to make multiple. Here is my code:```py
Get data
def getData():
with open("customCommands.json") as jsonFile:
data = json.load(jsonFile)
return data
data = getData()
for command in data:
@commands.command()
async def newCommand(ctx):# Somehow change newCommand to command["name"]
await ctx.reply(command["output"])
client.add_command(newCommand)
print(f"Added " + command["name"])
try changing ur interpreter using ctrl p > change interpreter
i tried importing it straight from python.exe (i dont even run my scripts in vscode, i use the cmd) and it throws
Dose it show if you do pip list?
lmao
i ran the same command 5 times and it didnt work, but waiting 10 minutes now it works, i didnt even run it agian or anything
@bot.command(help = "Shows the Guild the bot is in")
async def serverlist(ctx):
if ctx.author.id == ownerID:
msg = "\n".join(f"{x}" for x in bot.guilds)
embed = Embed(
title = "",
description = "",
color = col
)
embed.add_field(name = "All Bots Guilds", value = f"```\n{msg}\n```")
await ctx.send(embed = embed)
What should I type to use this command
How to fix
ownerID ?
it does give me 2 (same) warnings: WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
so i should probably solve those...
whats the error
define it
what ide is that
Replit
Are you using a phone π³
I cant, the bot is working with the error
Why not
Fancy
bro what
Since my laptop broken
oh lawd i'm having a heart attack
How to fix
if you do client = discord.Client then you must use client.guilds and not bot.guilds
whats wrong
Everything
can I add bot = commands.Bot(command_prefix="a!", intents=intents, status=discord.Status.online)
Where is ownerID coming from?
@slate swan
yeah
then embed is not dfined
kk
How to fix
Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 188, in on_message
await message.channel.send(content=None, embed=embed)
File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544, in _request
await resp.start(conn)
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", line 890, in start
message, payload = await self._protocol.read() # type: ignore
File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604, in read
await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
What exactly is the problem?
**aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
**
??
we know
its a api error
just gotta figure out whats causing it
It was for ADX
o
clearly I did put it in a code block but you asked for whats the problem so i bolded the line 4 u :)
Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 170, in on_message
while "redgif" in post.url or ".gifv" in post.url:
File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544, in _request
await resp.start(conn)
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", line 890, in start
message, payload = await self._protocol.read() # type: ignore
File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604, in read
await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer
Another error right here
**while "redgif" in post.url or ".gifv" in post.url: **
was the last traceback and error is
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer
ah
figured it out
the while loop makes too many requests
too fast
ownerID = 0
from discord import Embed
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
@bot.command(help = "Shows the Guild the bot is in")
async def serverlist(ctx):
if ctx.author.id == ownerID:
msg = "\n".join(f"{x}" for x in bot.guilds)
embed = Embed(
title = "",
description = "",
color = col
)
embed.add_field(name = "All Bots Guilds", value=f"β\n{msg}\n")
await ctx.send(embed = embed)
``` this kind of fix.. all the stuff that's underlined needs to be defined (set as in a variable) or imported (like `Embed`)
!d discord.AppInfo.owner also works
The application owner.
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Your not in a voice channel")
voice_channel = ctx.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
!d discord.ext.commands.Bot.application_info
await application_info()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the botβs application information.
voice_channel = ctx.voice.channel i have a problem with this line any1 can help
voice has no attribute
!d discord.Member.voice
property voice: Optional[discord.member.VoiceState]```
Returns the memberβs current voice state.
!d discord.VoiceState.channel
The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
It should be ctx.author.voice.channel
APIs of wha?
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
cause my api for vtuber image now took me about 5000ms to send
bruh
anything that u think thats gud
shit api π
ye, not related to this channel
yes it is related because it is about discord bot

u play LOL?
it does not make it related to channel topic, you are looking for APIs, right..?
kayle
yea
API for my discord bot
@commands.command()
async def foo(self, ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get("https://cdn.discordapp.com/emojis/742284778409164801.gif") as r:
res = await r.content()
await ctx.send(res)
Error :
Traceback (most recent call last):
File "C:\Users\xyz\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 882, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\xyz\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 910, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\xyz\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 182, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'StreamReader' object is not callable
I wanted the bot to send image in the provided url, I'll also want to pass this as a parameter inside create_custom_emoji like ctx.guild.create_custom_emoji(..., image=res, ...)
What am I doing wrong here?
- no
- lol takes too much time
How do I make a handler for this command?
content is an attribute I think
wild rift take less lmao
isinstance(error, discord.Forbidden)
ik, ive seen an ad for it before
i know
unfortunately, the person rage quit the server π
thanks you
lmao
Lmao
yes it is, the discord docs wanted me to pass in a byte like object but I am not sure how to do that using aiohttp, I've checked attributes of clientResponse under aiohttp to see anything related to byte like object but to no avail
:(
never seen greyblue in this channel before
How do I find the owner of the guild?
hm try reading the content
!d discord.AppInfo.owner
The application owner.
thanks
res = ...
await res.read()
it's wrong one
ctx.guild.owner
also
you need member intents for that
you have to enable it from the discord dev portal
yea, thanks
and enable it in your bot
ctx.guild.owner no need for the extra message attr
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="foo", intents=intents)
oh yea, oops
So my bots occasionally for some reason have a "breakdown" as I like to call it, where I'm suddenly getting errors that supposedly are from inside a package's file, and this time it even caused commands like pip list to stop working. I have set up a backup of the bot so it can still be used, but I'd like to know what's going wrong. It may be related to the asyncio package, as I've been able to fix issues by commenting it out, but I'm not sure if that package is actually important/used in my code, as some of my bots have it and others don't. I can't even remember when and why I added it... Let me know if you need any more information.
Error message: https://paste.pythondiscord.com/piwideyazu.sql
!paste paste error
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.
remove the () after .content
Did I do it right?
https://paste.pythondiscord.com/piwideyazu.sql
File "/home/allans/NeoBot Premium/cogs/sharding.py", line 13, in update_database latencies = self.bot.latencies AttributeError: 'Bot' object has no attribute 'latencies'
from discord.ext import commands as cmd
import traceback
import asyncio
from datetime import datetime
class Sharding(cmd.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.loop.create_task(self.update_loop())
async def update_database(self):
latencies = self.bot.latencies
if len(self.bot.shard_ids) == 0:
return
cluster_id = self.bot.shard_ids[0] % self.bot.config.per_cluster
shards = {id: {
"latency": latency,
"guilds": 0,
"users": 0,
"seen": datetime.utcnow(),
"cluster": cluster_id
} for id, latency in latencies}
for guild in self.bot.guilds:
try:
shards[guild.shard_id]["guilds"] += 1
shards[guild.shard_id]["users"] += guild.member_count
except:
pass
for id, shard in shards.items():
await self.bot.db.shards.update_one({"_id": id}, {"$set": shard}, upsert=True)
async def update_loop(self):
while not self.bot.is_closed():
try:
await self.update_database()
except Exception:
traceback.print_exc()
await asyncio.sleep(60)
def setup(bot):
bot.add_cog(Sharding(bot))
An small issue where the bot sends <StreamReader 8523 bytes> instead of the image.
f
you have Bot object , not AutoShardedBot
What do I even need asyncio for? What is it used for?
Is there some wizardry where we convert StreamReader to byte like object? 
try this:
import io
res = io.BytesIO(res)
await ctx.send(file = discord.File(res))
idk if it would work doe
discord.py library is based on asyncio
running async functions
so basically everything you do in it is asyncio
But do I need to import asyncio in my code?
no
yesh
So I can just throw that line out of- well this is confusing
what for?
Yes or no?
you need to import it
if not it will give an error
loaded the cogs but it wont recognize the commands inside the cog, what do i need to fix?
Actually it gives errors when I do import it
In fact, it even starts to give errors when I'm just trying to pip list... Somehow
could you show your code , and the error you get
@commands.command()
async def foo(self, ctx):
async with aiohttp.ClientSession() as cs:
async with cs.get("https://cdn.discordapp.com/emojis/742284778409164801.gif") as r:
res = r.content
res = io.BytesIO(res)
await ctx.send(file = discord.File(res))
Error :
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: a bytes-like object is required, not 'StreamReader'
Β―\_(γ)_/Β―
This is the error:
https://paste.pythondiscord.com/piwideyazu.sql
I don't even know what it's erroring on and I'm not planning to show my entire bot, sorry
yo kale
replit?
well atleast its private
replit is really unstable and buggy , thats the issue
if you run the same code on your device it will run well
yesh replit bad doe

Wait it's private?
I'm running literally the exact same code with the asyncio commented out and it's perfectly fine
not like anybody is gonna look at peoples shitty code if its public π
gimme your kales
hecker plan intensifies
iirc Private Repls got a dedicated IP
Ik haha
i dont think so
id never go for it and get a vps instead :^)
I can't run it on my own device. The bots need to be up 24/7, I'm just someone living with their parents doing this in their free time, I'm not allowed to leave my laptop on all the time to run like 5 bots.
why dont you just run the bot with asyncio removed if it actually is running and you're not using it
then find another host
its not like replit is the only free host
why did you import it there?
help-
show code?
code pls
I literally stated:
-I don't know if I need it, which is why I came here
-I don't remember why I added it
this and um
a im still new sorry
the command is in the __init__ function
move the command function outside the init function
GitHub Students get free replit hacker plans 
oh
wot
in other words "i got it too yay" lmao
It was the best I found at the time, it hardly ever gave me issues, and I can't just go swap now that I have the paid plan
Wait nvm, its for 3 months for new users ^^^
lmao
sad moment
But do I fully need to swap to the backup? Because the old one seems completely broken, even after removing the line
run all those 5 bots in a single script and deploy it to heroku
you cant run multiple bots on 1 script
you can
you can
but its messy af
I wouldn't say it's messy
Please. I already stated I can't just swap hosts.
just put all the bots in the event loop and run it
And I'd probably need to rewrite a lot, as the bots share a lot of function names but with different responses.
well since you dont want to share the code
and you are able to run it without asyncio , just remove asyncio and continue , thats all i can suggest
And fully swap to the backup?
Well, I've transferred everything to that and removed the (already commented out) asyncio
I selected it and there was no highlight anywhere in the file
So it's not mentioned anywhere else
yea so you're cool with running it without asyncio
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
future: <Task finished name='Task-97' coro=<Message.delete.<locals>.delete() done, defined at /usr/local/lib/python3.8/dist-packages/discord/message.py:1014> exception=ClientOSError(32, 'Broken pipe')>
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/message.py", line 1017, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544, in _request
await resp.start(conn)
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", line 890, in start
message, payload = await self._protocol.read() # type: ignore
File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604, in read
await self._waiter
I've deleted the broken version
try printing accountsfile
This error usually means you are running blocking code long enough for it to stop your network iirc
say what
you can stop your network with blocking code?
Err I worded it wrong
But your most likely blocking your connection to discord
Like how you can block your bot from sending heartbeats to the gateway, essentially making "dead"
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 170, in on_message
else:
File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 619, in _request
break
File "/usr/local/lib/python3.8/dist-packages/aiohttp/helpers.py", line 656, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
Interaction timeout?
yep
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'id'
```i get this error wen i try this in wavelink cogs...
my code
```py
async def play(self, ctx: commands.Context, *, track):
"""Play a song with the given search query.
If not connected, connect to our voice channel.
"""
if not ctx.guild.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
else:
vc: wavelink.Player = ctx.guild.voice_client
tracks = await wavelink.YouTubeTrack.search(query=f"{track}")
if not vc.is_playing():
await vc.play(tracks)
await ctx.reply(f"Playing {tracks}", mention_author=True)
return
vc.queue.put(tracks)
await ctx.reply(f"Added {tracks} to the queue.", mention_author=False)
if track.startswith("https://open.spotify.com/"):
if track.startswith("https://open.spotify.com/track/"):
track = await spotify.SpotifyTrack.search(query=f"{track}", return_first=True)
if not vc.is_playing():
await vc.play(track)
vc.queue.put(track)
elif track.startswith("https://open.spotify.com/playlist"):
await ctx.send("playlist meh")
async for partial in spotify.SpotifyTrack.iterator(query=f"{track}", partial_tracks=True):
if not vc.is_playing():
await vc.play(partial)
vc.queue.put(partial)
```how do i get this ryt?
await vc.play(tracks)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
i saw youtube somewhere in that
i mean
YouTubeTrack
iz literally this....i dont get how this is ytdl
soundcloud got no support for all the songs....turns out my taste for songs is UNIQUE...sooooooo yt is da last resort manz
Well wavelink also breaks ToS, sooo
f fomme ig
wavelink stopped being maintained as well
lavalink
how do i make an error handler if the person doing the command doesnt have this role
!d discord.ext.commands.CheckFailure this
exception discord.ext.commands.CheckFailure(message=None, *args)```
Exception raised when the predicates in [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") have failed.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
Simple Error Handling for ext.commands - discord.py - error_handler.py
I have a small problem with my buttons, if I press the button on a server, it responds on the another one that pressed the button a moment ago. Any idea how can I solve this?
await self.bot.get_guild(payload.guild_id).get_member(payload.user_id).remove_roles(self.bot.get_guild(payload.guild_id).get_role(744645354640637974))
```I like this
my mind thinking how many nonetypes this'll raise
self.bot.get_guild(payload.guild_id).get_member(payload.user_id) why this when payload.member exists?
I'll show you
!d discord.RawReactionActionEvent.member
The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
New in version 1.3.
ow yea
pycord
Pycord π΄οΈ
hmm
is there an alternative for on_ready?
cuz I need to send a message when the bot is up
and I shouldn't use on_ready right?
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
ah yes solution = more damn loops lagging the shit out of everything
Nah
bots normal ping already 3k
You know... My bot (HunAI) got like 5 tasks or smth running and it is in 99 servers but the bot's ping is about 120 or smth
How is ping relevant to compute time
3k? how do you even manage that
hm
fuck knows 
i use replit and it has like 30ms how tf do you get 3k ms
LMAO
Sooooo?
4gb drr3 2cores e-5
you can get a better one with 20 bucks if you got 3k latency from that
ping totally depends on your internet connection bro
20β¬ / year dude
thats cheap asf
people get servers with 50-100 MS ping with 5 USD lol
1.3β¬ / month
About 2 USD per month
ye ik, but if you got 3k ping from that..?
I host for free and I have better latency smh
ikr same
good question
aws?
no it's 24/7 free for me, not trial
500mb free memory and 65%cpu (what ever that means)
Probably a shared server?
that means suppose the CPU has 1.8 GHz speed, then u get to use a max of 65% of 1.8 GHz
help I'm being meh
embed.set_footer(icon_url=f"{guy.avatar.url}, itt: {message.channel.mention}")
In embeds.0.footer.icon_url: Not a well formed URL.
Don't know what that means, but ye more than 1 people use a server but everyone has the 500mb free etc (or they can buy vps)
80860.06ms rn
it only needs a url, not the itt thingy
8 seconds tf?
oh
Ungodly speeds
that should be in the text....
yea
and yet 35 ppl are using my bot lol
I wouldn't even pay 2 USD a month for whatever service you are using. They would need to pay me to even make me decide to use it
My avg latency is 80-100 (quite good imo for free)
replit?
whatever host that is, is pretty good then
I mean I could always change to my old pc, I've installed ubuntu server 21.04 on it and its got 8gb dd4 ram cpu i5
The only resource you really need to focus on is ram
Since all the caching is on the ram
it indeed is, I'm really happy that I found it
E.g guilds, users, members
but I mean that would cost more than 1.3β¬ / month in electric bill
Yea,
But tbh you should just switch your service providers
E.g AWS, GCP, Linode etc
They should have servers where you are?
I'm happy with the vds, it can 2 websites and 1 game server just fine. but for some reason my bot is just too much for it lol
I mean the websites are fast, no loading issues or anything
Might just be a problem with your bot then?
probably
You should setup a simple bot and benchmark it, compare with your original bot
you sure you don't use sync libs there and use async?
If the difference is vast you probably are doing something wrong in your original bot
Otherwise, it would just be an internet issue ig?
I mean the code is really messy, should probably rewrite it
but such a big internet issue on a paid host? Highly unlikely as long as it is a non trusted host
cuz I remember I had another bot, way more simple tho, max 30ms ping
@slate swan what is the website of the host?
hell yea its a untrusted host xd
its some romanian random host
Just going off the numbers Β―_(γ)_/Β―
Breh just use a better host
u r just wasting your money
you are using untrusted host?
you still pay for them
wym
They track your data and stuff
damn
Usually services just sell telemetry data, and that's how they can provide such cheap services
and most of the times people don't know about it? or smth
Yea most of the time ig
Discord also has telemetry
Don't even get me started on windows and telemetry
https://cdn.discordapp.com/attachments/833703485848420422/899924191040659476/IMG_20211019_103614.jpg this from the dudes discord
he running his stuff in his basement
wait it does? Never knew
Yea, I heard about it a while back for some stuff
Like when users call slash commands api/v9/science get's requested
Most likely telemetry or whatever
Well I did hear something related to NFT but never knew what was the whole story
what's that
Time to move to discord web again
Endpoint for telemetry/analytics
Ah okay
bruh my bot keeps going offline, tho its still running
enable logging
what are all those sticks
they look like ram sticks
# running = False
@client.event
async def on_ready():
for guild in client.guilds:
for channel in guild.channels:
if os.path.exists("/home/bot/adx/channel"+str(guild.id)) == True:
file = open("channel"+str(guild.id), "r")
if str(channel.id) == file.read():
file.close()
embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
embed.add_field(name="Reason for inactivity", value="Restart by developer", inline=False)
embed.add_field(name="Note", value="Small bug fixes || Added new categories", inline=False)
await channel.send(embed=embed, delete_after=60)
break
this was working before, any idea why it isn't anymore?
fuck
i think in the open you need to put /home/bot/adx/channel instead of just channel
How can I sleep 24h? I don't want to use seconds
also no need to say if os.path.exists() == True, just say if of.path.exists()
(It's a background task)
nope cuz the main.py is in /home/bot/adx
ik I just like to do it like that
oh then you need to just put channel in the os.path.exists
oh ok thats fine
yeah they are ram sticks (not mine tho)
they ddr3
what would someone ever need that much ram for
Its really not that much
its some romanian dudes hosting company, he has his servers in his basement
it's like 40 sticks, unless they're 1gb each...
@client.command()
@commands.check(is_it_me)
async def nicks(ctx):
guild = client.get_guild(756504534897000528)
while True:
for member in guild.members:
print(member)
await member.edit(nick=f"β¨γ»{member.display_name}")
WHY THIS DOESN'T WORK!
this work?
its apperently 512gb
so it is quite a bit
Where is that
please help me
intents?
he has a server with 288gb ram
They're max 8gb. If you're 40 figure is right (which it probably isn't) its max 320gb
That not a lot for server grade
client = commands.Bot(command_prefix='?', case_insensitive=True, intents = discord.Intents.all())
it's not right i went by eye, i counted up to 12 sticks and then that looked like a fourth of the sticks, so i just said 40, it's a decent guess tho, it should be between 30 and 50
It works for my welcomer
u got logging?
But I can't do it manually
640gb*
what kind
Guys could asyncio.sleep(86400) run into any issues?
It shouldn't
should I use time.sleep or asyncio.sleep inside a while loop
which array should I use for a tree command for a marriage cog
ok ty
I don't think so, except the general issue with that getting stopped because of your bot restarting
WHY IT DOESN'T WORKKKK
.
time.sleep isn't async. You would have to use asyncio.sleep
wont send the embedded message and no error help?
but asyinco.sleep doesn't stop the while loop, it just keeps repeating everything thats before the ayncio.sleep
remove embed color and try again
I think it has to be a string
why
oh alr
testing :/
no, it has to be an int or a discord.Color object
because the command raises an error when it tries to edit someone it cant
why I don't get the error tho
Is there a way to see why this isn't working?
idk your error handler eats it maybe
still wont
sorry can't help β€οΈ
whats is_it_me
you sure no error
nope
Just so no one do the command
wont give me an error
I think the error is, Because it can't change the nick of owner
Why not use the arg and kwarg arguments of the embed to add a description and the color?
i find it a bit messy
discord.Embed doesnt take any args though
only kwargs afaik
I just threw it out there in case it did
which array should I use for a tree command for a marriage cog
uhh... I'll get back to you on that
@client.command()
@commands.check(is_it_me)
async def nicks(ctx):
guild = client.get_guild(756504534897000528)
while True:
for member in guild.members:
if member.display_name != "SamTheNoob":
await member.edit(nick=f"β¨γ»{member.display_name}")
else:
pass
Im a fucking genius
wrong ngl
can I use a async def to stop a command?
ok i got it logged now, can I dm you the log? I've never used import logging so this shits not understandable for me
!paste u can use this
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.
How do you reset a nickname?
nick=None in member.edit
Wait what is the level?
& browser froze
set the level to WARNING not DEBUG
kk
hmm
idts
!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.
whats the code so when i ping my bot it responds with its prefix (i use discord.py)
use on_message event
and check if <@!yourbot'sid> is in the message
https://paste.pythondiscord.com/azequkeyeg.sql @maiden fable
Now thats a lot of errors
2021-12-19 18:44:31,730:WARNING:discord.gateway: Shard ID None heartbeat blocked for more than 50 seconds.
that's the issue. use aiohttp
Doesn't this mean something is blocking (Not async)?
and it is requests
nvm its praw
Kek called it
or why not use the JSON API
praw easier
Understandable
Isn't asyncpraw litteraly just praw but async
Yes
was answer to huntering
if on_member_ban as an event is not accessed, does that mean it never gets called in the source code?
Ah
I think he meant using asyncpraw/praw is easier than working with raw JSON data
I made a restart command it successfully restarts the bot, how can I make it edit that Rebooting message to Done after successful reboot here's the code py @bot.command() async def restart(ctx): ctx.message.author == "787149777103486986" await ctx.send("**Rebooting** ") os.system("clear") os.execv(sys.executable, ['python'] + sys.argv)
I think you forgot to add an if statement
wot
and .id returns an int, not a string
hmm
and ctx.author is enough
yeah I'm aware
not needed ig
Currently anyone can restart the bot
just fixed
.
You need an if statement
oh oke
fck
while True:
for member in guild.members:
try:
if member.nick.startswith("β¨"):
pass
else:
await member.edit(nick=f"β¨γ»{member.display_name}")
except:
pass
Will it pass if it's already done?
can I get some context?
while True 
yeah :'(
what should I use
?
tasks
urgh...
where's the path to tasks
your indent 
ok what ever
huh
thanks for the help
!d discord.ext.tasks.Loop @final iron
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
ext.tasks is the submodule
Ah
Lmao
but I wrote 300 lines in 2 hours so I think it's acceptable
Idk what u tryna do, soo uhhhh
what I could have done before to get random submission from a subreddit
sub = reddit.subreddit("insertnsfwsubreddithere").random()
What i gotta do now
sub = await reddit.subreddit("insertnsfwsubreddithere")
async for submission in sub:
How can I compare the datetimes of when a vc was created, and when 'the' command is issued
pls give better solution than for loop
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
I know I have created_at, but what format is datetime in and how can I compare
u can use datetime.datetime.utcnow() to get the current date and time
right, so how can I check if its x minutes after the creation of channel x
andy gave u the answer π
TypeError: object of type 'Subreddit' has no len()
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 206, in on_message
post = random.choice(postr)
File "/usr/lib/python3.8/random.py", line 288, in choice
i = self._randbelow(len(seq))
Cheers, I understand that would see if its created before or after, but how can I specify minutes
try doing (await reddit.subreddit(...)).flatten()
at least 5 minutes wouldnt simply be if datetimenow >= datetime_of_creation + 5 right? 
since its an object
AttributeError: 'coroutine' object has no attribute 'flatten'
edited my message
guys, how do I make it return the time only ,-,
for act in member.activities:
if isinstance(act, discord.Spotify):
embed = discord.Embed(title=f"{member.name}'s spotify status", color=member.color)
print(act.start.astimezone(pytz.timezone("Asia/Calcutta")))
AttributeError: 'Subreddit' object has no attribute 'flatten'. 'Subreddit' object has not been fetched, did you forget to execute '.load()'?
I just lost 5 braincells seeing that code
do what the error says lol
leaves
fuck this I'll use the annoying for loop
bruh
why can't asyncpraw have .random()
dpy internally calls the events, your linter doesn't know about that
In range(60).
!d datetime.datetime.hour
In range(24).
!d datetime.datetime.second
In range(60).
it does
it was.... indented wrong
really not helpful of what I was trying to do
I told u the issue tho 
discord.Spotify?
yesh
u need the current time, u can do time.hour, time.minute and time.second and stuff, but then idk shit about datetime module so uhhh
mb, i should also get some sleep lol
ahhh, thanku
a shorter version of discord.ActivityType.listening
I see
!d discord.Spotify
class discord.Spotify```
Represents a Spotify listening activity from Discord. This is a special case of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that makes it easier to work with the Spotify integration.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activityβs hash.
str(x) Returns the string βSpotifyβ.
istg google colab gonna make me pull all my hair out
hahaa wtf by breaking something I fixed the message I had on_ready
no idea what I even did
but it worked
lovely python
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
cant be that cuz it was working before
@maiden fable Does the .minutes attribute return an integer for datetime?
yea iirc
easy
also thx huntering
!e
import datetime
time = datetime.datetime.utcnow()
print(time.minute)
print(type(time.minute))
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
001 | 25
002 | <class 'int'>
what datatype does context.author return?
See
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the userβs hash.
str(x) Returns the userβs name with discriminator.
Depends if the command is in DMs or Guild
hmm
Hunter*
The userβs username.
compare this
Try printing context.author.name
okey
how do I get the purple streaming status
@client.command(name = "terminate")
async def terminate(context):
print(str(discord.User.name))
if discord.User.name == "PythoNub#8527":
import sys
embed = discord.Embed(title = "Shutting down :(")
embed.set_footer(text = context.author + "killed me ")
await context.message.channel.send(embed=embed)
sys.exit()
else:
embed = discord.Embed(title = "Haha Nice try")
embed.set_footer(text = ":)")
await context.message.channel.send(embed = embed)
!d discord.ActivityType.streaming
A βStreamingβ activity type.
@slate swan ^
returned the same thing
what should I put in discord.Status then?
show code
cuz activity should only give streaming: thing
here
!d discord.Status.idle or smth
The member is idle.
yea that too
idle is the yellow status tho
how would I convert a set that has one object to a role object
wait
I just take set_name[0]

;(
!d discord.Message.author
after converting it to a list!
Thatβs my boy/girl
How to fix this?
Code
sec = round(error.retry_after)
cooldownembed = discord.Embed(title="", color=discord.Color.blue())
cooldownembed.add_field(name="β²οΈ Cooldown",value=f'The command {on_command_error} is still on cooldown for **{convert(sec)} Seconds**'.format(ctx.command.name, error.retry_after))
Why are you using f strings and format?
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this contextβs command. Shorthand for Message.author
hey how can I make people with admin permissions bypass the channel in which command is supposed to be used, suppose this is my code ```py
@bot.command()
async def hi(ctx):
if ctx.channel.id == 917866202968236052:
return
await ctx.send("Hi")
!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.
Using dpy2.0 trying to add a button before a select dropdown in my view, getting an error as drop-down size is 5, adding a button to that row surpasses the limit
How would I go about fixing said issue?
(I would like to move the drop-down 1 row down)
If channel is this or ctx.channel.permissions_for(ctx.author).administrator may work
Why 2.0 and not a fork?
It works fine and its native
If ctx.channel.id == ID or ctx.member.role == role
@bot.command()
async def hi(ctx):
if ctx.channel.id == 917866202968236052:
ctx.channel.permissions_for(ctx.author).administrator
return
await ctx.send("Hi")``` do you mean like this?
I recommend using a fork like disnake
@maiden fable still keeps going offline, here is another log
https://paste.pythondiscord.com/jetayiwufa.sql
I didn't get it how will admins bypass?
No no put the permissions for as βorβ in the it statement
I've already written most of my bot, what benefit would I have using a fork?
again blocking code
So like if ctx.channel.id == ur channel id or ctx.channel.permissions_for(ctx.author).administrator
what could be blocking the code
Well most forks have better buttons and you will not need any third party lib and most forks have slashcommands and especially disnake is always up to date and is not hard to change to it you just replace the word discord with disnake and your basically working with disnake already or you can just import disnake as discord which i dont quite recommend but buttons for disnake are very easy and have github examples if you have any questions about them
so py @bot.command() async def hi(ctx): if ctx.channel.id == 917866202968236052 or ctx.channel.permissions_for(ctx.author).administrator: return await ctx.send("Hi") this?
while loop maybe?
Yes but remember the colon after the if statement
edited
https://github.com/DisnakeDev/disnake/blob/master/examples/views/button/confirm.py
Its the same as dpy2.0 from what I can see
Does dpy2.p use ui.view not quite sure but ig it will be easier for you
Ah i see it does
Mhm
that is blocking 
But it doesnt have slash commands afaik
Facts
maybe if I make a timer, so when it reaches 90seconds it breaks and starts again after running the whole code?
Use threads and an await sleep in main that waits for the blocking code to either update or finish
@torn sail colon shows invalid syntax
its supposed to be a infinite loop
Using dpy I'm sure you can create a task that loops forever
hmm but shouldnt if statements end with a color
yes
can you screenshot ur code?
90 seconds too much
shouldn't be more than 5-10s
I'll send it here
Using task.loop decorator
This is spam command restricted to a single channel, but I just want admins to use it in any channel py @bot.command() @commands.cooldown(1,30,commands.BucketType.guild) async def spam(ctx, amount : int, *, message=None): if ctx.channel.id == 917866202968236052: return limit = 15 if amount > limit: await ctx.send(f"<:_:919194636906561548> **The amount provided `{amount}` is too big! It needs to be less then 15.**") return else: for _ in range(amount): await ctx.send(message)
Welp you'll need to specify the repeat rate tho
You can use a decorator for permission
why do you want to spam...
he wants permission or channel

You can make a custom check too
yes he could do that
Can someone explain to me why its not defined even after I defined it?
not related to this channel?
Well its a bot so ya kinda
wait but by doing if ctx.channel.id == id: and returning doesnt it make it so it can be used in any channel but that channel
does not seem like a discord bot :/
You are right it is a macd trading bot, if this is not the right place, where could i ask this question? Thanks in advance!
so should be
if ctx.channel.id == 917866202968236052 or ctx.channel.permissions_for(ctx.author).administrator:
# Do your stuff here
#βο½how-to-get-help is a good place to get started π
I tried this earlier
but it doesn't work shows invalid syntax
then idk
found it, something like this for custom check:
def is_guild_owner():
async def predicate(ctx):
if not ctx.guild.owner_id == ctx.author.id:
raise commands.CommandError("This command can only be used by server owner!")
return True
return commands.check(predicate)
are you making a new line after the or?
it seems like so
for him it could be
def is_channel_or_admin():
async def predicate(ctx):
return ctx.channel.id == channelid or ctx.author.permissions_for(ctx.author).administrator
return commands.check(predicate)
^
now = datetime.now()
current_time = now.strftime("%S")
while m:
current_time2 = now.strftime("%S")
current_time3 = int(current_time)
current_time3 += 10
while current_time3 >= int(current_time2)
too confusing for me, would this work
as a timer
^
hold up, i think i got something
For what?
cuz the while loop is blocking the code
cuz its infinite loop
and im tryna break the loop when 10s has passed
Use tasks
and create task was too complicated for me
timeout = time.time() + 60
while True:
await asyncio.sleep(0.1)
if (timeout < time.time()):
#do something
A task loop is an async version of a while loop
Not if, while*
@bot.command()
async def sendp(ctx):
guild = bot.guilds()
for member in guild.members():
print(member)
``` why does not work ;/
``` ret = await coro(*args, **kwargs)
File "c:\Users\sdziu\Desktop\Python\Discord\nsfw_bot.py", line 27, in sendporn
guild = bot.guilds()
TypeError: 'list' object is not callable```
whats the while True for?
guild.members
well thx my issue is fixed @torn sail
Take out the parentheses in bot.guilds
And In guild.members
0.o welp, pulled it from my code, tho its got couple other paramaters to break on, while also adding to the timeout . - .
emulates a task that lasts forever
well, its a loop that never ends
yeh says the same thing
I'll just leave ;-;
So you made guild.members() to guild.members
yeh
timeout = time.time() + 60
while autoporn:
await asyncio.sleep(0.1)
if (timeout < time.time()):
if message.channel.is_nsfw():
else:
break?
Is the error the same?
; - ; welp, not sure if i can implament it that way was what i meant. .
srry
yeh raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'members'
so i gotta use tasks huh
Fine, its in a while loop, which it shouldnt be in, its fine
damn this gonna suckk never used em before
Oh are you trying to get all the members in all the guilds?

reading these messages gives me a headache
This is the most insane channel in the whole server, so undertandable
@slate swan so bot.guilds returns are list of guilds and the list doesnβt have an attribute members but if you go through each guild then the guild will have an attribute members
I make my messages' readability harder than they are supposed to be so....
mee' too
||That's nice||
ahem ahem can we stop this ahem ahem
no just the one guild
||!ot||
So doing bot.guilds gets all the guilds the bot is in
then what do i do lmfao
yes
So are u trying the get the guild the command is run in or a specific guild?
oof
Look okay its already 12 midnight here and I am already on the edge of losing my sanity so it would be better if u don't joke with me rn with all those things, thanks
11:58* :p
OK THANKS
Woh
im trying to get the members from the guild the command is executed
anyways
Looks quite nice on hunter
then it would be
for member in ctx.guild.members:
print(member)
!d discord.ext.tasks.loop @slate swan
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Welcome
See the docs

