I'm trying to make a command that allows the user to update a reason on a warn to something else and I don't know how to update documents in mongodb
check = list(warndb.warn_logs.find({"case_id": caseid}))
for w in check:
reason = w.get('reason')
caseid = w.get('case_id')
change = {{"reason": reason}, {"$set": {"reason": update}}}
w.update(change, upsert=False)
embed = discord.Embed(color=embedcolor, title="Successfully updated reason", description=f"Updated reason for case {caseid}")
embed.add_field(name="**Before:**", value=f"{reason}", inline=False)
embed.add_field(name="**Updated To:**", value=f"{update}", inline=False)
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed)
return
Here's the main code that I have to update documents but I'm getting a couple of errors and I don't know how to update documents. please help
So please provide full trace back but here is the code for update your mongo also check documention : Mongo doc.
In a cog it could look like this - arg would be the case id eg "!update_warn 123" then the arg would be 123 and also the case id
cluster = MongoClient('Your mongo link')
collection_name = cluster["Database Name"]["Collection Name"]
#commands.command()
async def update_warn(self,ctx,arg):
check = collection_name.find_one({"case_id": arg})
if check is None:
await ctx.reply("No Case was found!")
else:
reason = check['reason']
caseid = check['case_id']
update = "Your Updated Reason"
collection_name.update_one({'case_id':arg},{'$set':{'reason': update}})
embed = discord.Embed(color=embedcolor, title="Successfully updated reason", description=f"Updated reason for case {caseid}")
embed.add_field(name="**Before:**", value=f"{reason}", inline=False)
embed.add_field(name="**Updated To:**", value=f"{update}", inline=False)
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=embed)
Related
#tree.command(name = 'redeem', description = 'Redeems A Members Key')
async def redeem(interaction: discord.Interaction, key: str, member:discord.Member):
with open("bkeys.txt") as f:
if key in f.read():
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Sorry, this key has been blacklisted")
await interaction.response.send_message(embed=em)
return 0
with open("keys.txt") as f:
if key in f.read():
role = interaction.guild.get_role(1071561081685811210)
await member.add_roles(member, role)
em = discord.Embed(color=0x008525)
em.add_field(name="Key Redeemed", value="Key has now been redeemed")
await interaction.response.send_message(embed=em)
f = open("ukeys.txt", "w")
f.write(key)
f.write('\n')
else:
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Inputed key has already been used!")
await interaction.response.send_message(embed=em)
Error
**This has been a command I have been trying to work on its just the add roles will not work, btw im new to python so I don't know much sorry, so if anyone could just drop the code please.
**
I tried changing the (1071561081685811210) to my role name ("Buyer") and asking for help but I didn't understand.
like bruh has said you should change
member.add_roles(member,role)
to
member.add_roles(role)
Unless there is a way to do it through discord.Member with what im currently doing?
current code..
#tasks.loop(seconds = 5) # repeat after every 60 seconds
async def checkAFK():
global rTotalPlayers
global cTotalPlayers
with open('playerPop.json') as f:
playerPop = json.load(f)
msgChannel = await client.fetch_channel(variables['pickup'])
for i in list(cTotalPlayers):
cTotalPlayers[i] = cTotalPlayers[i] - 1
if(cTotalPlayers[i] < 0):
member = await client.fetch_user(i)
#print(member.activities)
print(i)
del rTotalPlayers[playerPop[str(i)][0]]
del cTotalPlayers[i]
await msgChannel.send("<#" + str(i) + "> has been removed from the pickup due to being AFK.")
print(cTotalPlayers)
PopulateTable()
await msgChannel.send("```" + msg + "```")
print(cTotalPlayers)
What im trying to do is loop through a dictionary of players and after 60 seconds.. (in this case 5 just for testing purposes) itll subtract one.. what i wanna do is when it gets to 0.. i want it to check whether or not they have a green or moon by their name.. if moon and less than 0, itll remove them from a "pickup game". I am trying to find this currently thru await client.fetch_user and the commented line is where im checking outputs.. anyone know how to do it via the approach im already taking? Thanks
Above is fixed.. Next problem is getting the status to show correctly.. always showing offline.. code below.. dev portal stuff: https://imgur.com/a/EA3deJT
intents = discord.Intents.all()
intents.members = True
intents.presences = True
#intents = discord.Intents(members = True, presences = True)
client = commands.Bot(command_prefix = ["!", "+", "-"], case_insensitive=True, intents= intents)
You can get their status by using Member.status
This returns a Status object where the property returns a True or False value.
status = user.status
if status.online or status.idle:
pass # Do something here
Hi I'm getting an error that occurs when trying to add the timestamp. I keep getting the error asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "18" and this line end_date = duration + dt.datetime.now(bst) # timestamp seems to be the culprit however I'm unsure why this is the case.
Here is what I'm working with:
if time is not None:
conn = await asyncpg.connect(DATABASE_URL)
async with conn.transaction():
await conn.fetch(f"SELECT time FROM blacklist WHERE username={member.id}")
duration = find_date(time)
bst = pytz.timezone('Europe/London')
end_date = duration + dt.datetime.now(bst) # timestamp
fmt_date = end_date.strftime("%#d %b %Y, at %I:%M%p")
await conn.fetch(f"UPDATE blacklist SET time={end_date} WHERE username={member.id}")
await member.add_roles(restricted, reason=f'Restricted role added by {author.name}')
await member.remove_roles(members)
await conn.close()
msg = f"{member} has been restricted until {fmt_date}."
embed = discord.Embed(title="Restricted", description=msg, colour=author.color)
await ctx.send(embed=embed)
return
You don't pass the arguments in f-strings when dealing with SQL queries, the syntax for query arguments in asyncpg is $n, also I see that you're using the Connection.fetch method but you're simply updating the table, I'd suggest you to use Connection.execute
Your code fixed:
end_date = # Should be a datetime.datetime instance
await conn.execute("""
UPDATE blacklist
SET time = $1
WHERE username = $2
""", end_date, member.id)
Removing timezone awareness
end_date = # `datetime.datetime` instance
naive = end_date.replace(tzinfo=None)
await conn.execute("""
UPDATE blacklist
SET time = $1
WHERE username = $2
""", naive, member.id)
References:
Connection.execute
PS: Don't create a new connection everytime you want to use it, normal practice is to have one long-term database connection
So I am using disputils and I've made a pagination embed. however, after it gets inactive the reactions get auto removed by the bot. I want to make the bot remove the whole embed but I've tried a lot of things such as using delete_after=(float) and even asyncio but it doesn't seem to be working.
#commands.group(aliases = ['ra'])
async def red(self, ctx):
if ctx.invoked_subcommand is None:
default = discord.Embed(title="`test`",color=discord.Colour.dark_red())
default.set_image(url="foo")
default.set_footer(text="Image by| user")
v1 = discord.Embed(title="example", description='test', color=discord.Colour.dark_red())
v1.set_footer(text="Info taken from| website")
v2 = discord.Embed(title="spam", description="foo" ,color=discord.Colour.dark_red())
v2.set_footer(text="Info taken from| website")
embeds = [
default,
v1,
v2,
]
paginator = BotEmbedPaginator(ctx, embeds)
await paginator.run()
I tried using delete_after(float) inside the paranthesis of await paginator.run() doesn't work. tried using it asycnio format and got an error Instance of 'BotEmbedPaginator' has no 'delete' member. Any help would be appreciated.
Just use DiscordUtils
Here is an example:
#commands.command()
async def paginate(self, ctx):
embed1 = discord.Embed(color=ctx.author.color).add_field(name="Example", value="Page 1")
embed2 = discord.Embed(color=ctx.author.color).add_field(name="Example", value="Page 2")
embed3 = discord.Embed(color=ctx.author.color).add_field(name="Example", value="Page 3")
paginator = DiscordUtils.Pagination.CustomEmbedPaginator(ctx, remove_reactions=True)
paginator.add_reaction('⏮️', "first")
paginator.add_reaction('⏪', "back")
paginator.add_reaction('🔐', "lock")
paginator.add_reaction('⏩', "next")
paginator.add_reaction('⏭️', "last")
embeds = [embed1, embed2, embed3]
await paginator.run(embeds)
I'm doing a python bot for discord. it create an delete channel according to player instructions.
I want to create a garbage collector that test all the server.channels and delete the outdated one.
I do :
async def waitTimer():
while True:
await asyncio.sleep(10)
regex = re.compile(r"[0-9]*_[a-z0-9]*-[0-9]*") #nom des channels de raid
for cCurrent in client.get_all_channels():
if regex.match(cCurrent.name):
numRaid = int(cCurrent.name[0])
cRaidCurrent = cRaids[numRaid]
date = datetime.datetime.now()
print (cRaidCurrent.raid.fin.timestamp())
print (date.timestamp())
if cRaidCurrent.raid.fin < date:
if cRaidCurrent.retirerRaid():
cId = cRaidCurrent.com.id
await removeFromListe(cRaidCurrent)
await client.delete_channel(client.get_channel(cId))
cCurrent = 0
Sometimes it pass and sometimes I get this error :
for cCurrent in client.get_all_channels():
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 581,
in get_all_channels
for channel in server.channels:
RuntimeError: dictionary changed size during iteration
If I understand it clearly the client.get_all_channels is a dictionary and I can't remove the channels during the iteration ... So the question is what other possibilities do I have to remove those channel ?
Thanks Patrick Haugh for the answer that work perfectly.
In the end the deleting operation needs to be done in 2 times. Here is the code if anyone needs it :
for cCurrent in client.get_all_channels():
if regex.match(cCurrent.name):
numRaid = getNumChannel(cCurrent.name)
cRaidCurrent = cRaids[numRaid]
now = datetime.datetime.now()
if cRaidCurrent.raid.fin < now:
toDelete.append(cRaidCurrent)
for cRaidCurrent in toDelete:
cId = cRaidCurrent.id
cRaidCurrent.retirerRaid()
await removeCRaid(cRaidCurrent)
del cRaids[cId]