Discord Py Tempban - discord.py

#loop(seconds=10)
async def tempun(client):
db_name = "database/tempban.db"
db = await aiosqlite.connect(db_name)
try:
cur = await db.execute("SELECT * FROM tempban")
fetch = await cur.fetchall()
cur_time = datetime.utcnow()
for row in fetch:
ban_time = parser.parse(row[2])
print(ban_time)
if cur_time >= ban_time:
unbanuser = int(row[1])
guilduser = int(row[0])
try:
member = discord.Object(id=unbanuser)
guild = await client.fetch_guild(guilduser)
except Exception as e:
print(e)
try:
await guild.unban(member, reason="Tempban expired")
deletetime = await cur.execute("delete from tempban where guild_id = ? AND user_id = ? returning *", (guilduser, unbanuser,))
await db.commit()
except Exception as e:
print(e)
except Exception as e:
print(e)
The Code won´t Give any Errors it does nothing it prints the datetime from a user of my database all database values are there.

A good way is to use the asyncio library.
import asyncio
async def tempun(client):
# get data from the database
await asyncio.sleep(seconds_to_sleep)
await guild.unban(user, reason)
# delete from database
The tempun function can be called in the ban command or wherever it needs to be triggered

Related

Telegram Bot UNCLOSED CLIENT

Basically I was doing a small bot for telegram to send pictures from a subreddit, but it gives me an error which I don't know how to fix. Everything where it says (not shown) is something I can't show due to it being something with which anyone could use it under something I created, but I guess you don't really need it.
client_session: <aiohttp.client.ClientSession object at 0x000001555709DD90>```
config.py:
```settings = {
"CLIENT_ID": "(not shown)",
"SECRET_CODE":"(not shown)",
"TOKEN":"(not shown)"
} ```
telegram_bot.py:
```import asyncio
import aiohttp
import config
import asyncpraw
from aiogram import Bot, types
API_TOKEN = config.settings["TOKEN"]
CHANNEL_ID = -1001374273592
bot = Bot(token=API_TOKEN, parse_mode=types.ParseMode.HTML)
reddit = asyncpraw.Reddit(client_id=config.settings["CLIENT_ID"],
client_secret=config.settings["SECRET_CODE"],
user_agent="random_raddit_bot/0.0.1")
mems = []
TIMEOUT = 5
SUBREDDIT_NAME = "memes"
POST_LIMIT = 1
async def send_message(channel_id: int, txt: str):
await bot.send_message(channel_id, text)
async def main():
while True:
await asyncio.sleep(TIMEOUT)
memes_submissions = await reddit.subreddit(SUBREDDIT_NAME)
memes_submissions = memes_submissions.new(limit=POST_LIMIT)
item = await memes_submissions.__anext__()
if item.titles not in mems:
mems.append(item.title)
await send_message(CHANNEL_ID, item.url)
asyncio.get_event_loop().run_until_complete```

Exception Fixing ban command discord.py

I recently made a ban command for my bot but its not working, can anyone help? whenever i do !ban it just gives the exception and member.kick is blacked out, also i user kick insted of ban because of debugging purposes
Thanks!
Code:
#commands.command()
async def ban(self, ctx, member:nextcord.Member,*, reason="No Reason Provided"):
try:
if reason == None:
embed = nextcord.Embed(title="Member Banned!", description=f"{member.mention} has been banned from '{ctx.guild}'\n Reason: `No Reason Provided`", colour=BLUE_COLOUR)
embed.timestamp = datetime.datetime.utcnow()
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/942086556980764722/967720168199426069/Ban_Command.gif")
await ctx.reply(embed=embed)
await member.kick(reason=reason)
else:
author = ctx.message.author.name
SendConfirmation = nextcord.Embed(title="Member Banned! ", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**", color=GOLD_COLOUR)
SendDM = nextcord.Embed(title="You Have been Banned", colour=BLUE_COLOUR)
embed.add_field(name="Server Name", value=f"{ctx.guild.name}", inline=True)
embed.add_field(name="Reason", value=f"{reason}", inline=True)
embed.timestamp = datetime.datetime.utcnow()
await member.send(embed=SendDM)
await ctx.reply(embed=SendConfirmation)
except Exception:
ErrorEmbed = nextcord.Embed(title="Something Went Wrong", description="There was an error trying to perform this command.", colour=ERROR_COLOUR)
ErrorEmbed.timestamp = datetime.datetime.utcnow()
await ctx.reply(embed=ErrorEmbed)
return
There were 2 issues with the code:
Your reason argument was never none because it was set by default on "No Reason Provided" so you would never use the if statement
you created the variable SendDM and then used the embed function on a new variable that was never defined (called embed)
#commands.command()
async def ban(self,ctx, member:nextcord.Member,*, reason=None):
if reason == None:
embed = nextcord.Embed(title="Member Banned!", description=f"{member.mention} has been banned from '{ctx.guild}'\n Reason: `No Reason Provided`")
embed.timestamp = datetime.datetime.utcnow()
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/942086556980764722/967720168199426069/Ban_Command.gif")
await ctx.reply(embed=embed)
await member.ban(reason=reason)
else:
author = ctx.message.author.name
SendConfirmation = nextcord.Embed(title="Member Banned! ", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**")
SendDM = nextcord.Embed(title="You Have been Banned")
SendDM.add_field(name="Server Name", value=f"{ctx.guild.name}", inline=True)
SendDM.add_field(name="Reason", value=f"{reason}", inline=True)
SendDM.timestamp = datetime.datetime.utcnow()
await member.send(embed=SendDM)
await ctx.reply(embed=SendConfirmation)
await member.ban(reason=reason)
This code should work, I tested it on my machine, I took away embed colors and the try and except block but you can add them back.
One last thing, I suggest to remove the try and except block and handle errors with actual error handlers. You can find how to use them in the documentation of the nextcord library.

Allow only two user to use a command discord bot py

Hi I want to use the command for only 2 users with their user id can you help me pls there is my code :
python
#bot.command()
async def sub(ctx, vintedurl):
x = await ctx.channel.create_webhook(name="Discord-test")
with open("config.json", 'w+') as configedit:
configs["suburl"][str(x.url)] = {}
configs["suburl"][str(x.url)]["url"] = str(vintedurl)
configs["suburl"][str(x.url)]["salon"] = str(ctx.channel.name)
json.dump(configs,configedit,indent=4)
await ctx.send("Webhook ajouté avec le lien !")
You can either check in your command directly, like this:
#bot.command()
async def sub(ctx, vintedurl):
if ctx.author.id not in (123, 456): # your desired IDs here
return
x = await ctx.channel.create_webhook(name="Discord-test")
with open("config.json", 'w+') as configedit:
configs["suburl"][str(x.url)] = {}
configs["suburl"][str(x.url)]["url"] = str(vintedurl)
configs["suburl"][str(x.url)]["salon"] = str(ctx.channel.name)
json.dump(configs,configedit,indent=4)
await ctx.send("Webhook ajouté avec le lien !")
Or you could also create your custom check:
from discord.ext import commands
def custom_check(ctx):
return ctx.author.id in (123, 456) # your desired IDs here
#bot.command()
#commands.check(custom_check)
async def sub(ctx, vintedurl):
x = await ctx.channel.create_webhook(name="Discord-test")
with open("config.json", 'w+') as configedit:
configs["suburl"][str(x.url)] = {}
configs["suburl"][str(x.url)]["url"] = str(vintedurl)
configs["suburl"][str(x.url)]["salon"] = str(ctx.channel.name)
json.dump(configs,configedit,indent=4)
await ctx.send("Webhook ajouté avec le lien !")
Docs for custom checks: https://discordpy.readthedocs.io/en/master/ext/commands/api.html?highlight=check#discord.ext.commands.check
You can use simple if else to check the ctx.author.id :)
#bot.command()
async def onlytwopplcanuseme(ctx):
user_ids = [1234567890123456, 1234567890123456] # Replace the two user IDs here
if ctx.author.id in user_ids:
await ctx.reply("Approved!")
else:
await ctx.reply("Not approved!")

Python Socket.io event handling

I'm a complete beginner when it comes to socket, so please bear with me if the question seems too trivial for you.
The following is a code that i found on GitLab and I'm trying to understand
import os
import logging
import uuid
import socketio
from aiohttp import web
import sys
sys.path.append('.')
logging.basicConfig(level=logging.WARN,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')
# Home page
async def index(request):
index_file = open('examples/rasa_demo/templates/index.html')
return web.Response(body=index_file.read().encode('utf-8'), headers={'content-type': 'text/html'})
# Action endpoint
async def webhook(request):
"""Webhook to retrieve action calls."""
action_call = await request.json()
try:
response = await executor.run(action_call)
except ActionExecutionRejection as e:
logger.error(str(e))
response = {"error": str(e), "action_name": e.action_name}
response.status_code = 400
return response
return web.json_response(response)
# Web app routing
app = web.Application()
app.add_routes([
web.get('/', index),
web.post('/webhook', webhook),
web.static('/static', 'examples/rasa_demo/static')
])
# Instantiate all bot agents
bots = BotFactory.createAll()
# Websocket through SocketIO with support for regular HTTP endpoints
sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*')
sio.attach(app)
#sio.on('session_request')
async def on_session_request(sid, data):
if data is None:
data = {}
if 'session_id' not in data or data['session_id'] is None:
data['session_id'] = uuid.uuid4().hex
await sio.emit('session_confirm', data['session_id'])
#sio.on('user_uttered')
async def on_user_uttered(sid, message):
custom_data = message.get('customData', {})
lang = custom_data.get('lang', 'en')
user_message = message.get('message', '')
bot_responses = await bots[lang].handle_text(user_message) #await BotFactory.getOrCreate(lang).handle_text(user_message)
for bot_response in bot_responses:
json = __parse_bot_response(bot_response)
await sio.emit('bot_uttered', json, room=sid)
What I'm trying to understand is how do the event handlers catch or events like 'session_request' or'user_uttered' when they were never emitted.
Thank you.

Discord.py: Trying to do an action depending on user reaction

This is the code:
import asyncio
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = ".")
Token=""
#client.command()
async def react(ctx):
message = await ctx.send("Test")
await message.add_reaction("<💯>")
await message.add_reaction("<👍>")
user=ctx.message.author
def check(reaction, user):
user == ctx.message.author and str(message.emoji) == '💯'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('💯')
else:
await channel.send('👍')
client.run(Token)
The problem is that I always get an error "'await' outside async function", and the a of "reaction, user = a" get highlighted. Thank you for any help.

Resources