name 'user' is not defined mentions - discord.py

I am trying to get when a user pings another user! Get the users mention and add a point into the database! Although User is not defined! And cant register any points for the user getting pinged!
import sqlite3
from discord.ext import commands
client = commands.Bot(command_prefix = "ping")
POINTS = 0
#client.event
async def on_ready():
db = sqlite3.connect("ping.sqlite")
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS main(
user_id TEXT,
points INTERGER
)
''')
print("Looking for Pings!")
#client.event
async def on_message(message):
USER = user.mention.id
db = sqlite3.connect("ping.sqlite")
cursor = db.cursor()
cursor.execute(f"SELECT user_id FROM main WHERE user_id = {USER}")
result = cursor.fetchone()
if result is None:
sql = ("INSERT INTO main(user_id, points) VALUES(?,?)")
val = (USER, POINTS)
elif result is not None:
sql = ("UPDATE main SET channel_id = ? WHERE guild_id = ?")
val = (ctx.guild.id, channel.id)
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
client.run(TOKEN)

if len(message.mentions) > 0:
all_pinged_users = [user for user in message.mentions]
#it will give all pinged user object in all_pinged_users and you can do anything with that!
else:
#no user is pinged
you can use this simple if statement to find if any user is pinged in the message! and the message.mentions is in the type of list of all pinged users in that specific message
you can also iterate through the message.mentions to get all pinged user

Related

Telegram bot is running, but does not retrieve data from the database

trying to output data from sql to telegram bot. bot is
running(sending message.answer), but after that nothing happens and
shows no error. using pycharm and xampp. it is my first code
import logging
import mysql.connector
from aiogram import Bot, Dispatcher, executor, types
API_TOKEN = 'token'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="php"
)
mycursor = mydb.cursor()
#dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
await message.answer("Hi!\nEnter name:")
# works up to this line
#dp.message_handler(content_types=['text'])
async def send_msg(message: types.Message):
mycursor.execute(
"SELECT surname, age, year, city, phone FROM list WHERE name ='{}'".format(message.from_user.id))
# fetching the rows from the cursor object
result = mycursor.fetchone()
for x in result:
await message.answer(x)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Rewrite your code like this
#dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message, state: FSMContext):
await message.answer("Hi!\nEnter name:")
# works up to this line
await state.set_state("get_name")
#dp.message_handler(state="get_name")
async def send_msg(message: types.Message, state: FSMContext):
mycursor.execute(
"SELECT name FROM users WHERE name ='{}'".format(message.from_user.id)) # message.text should be here?
result = mycursor.fetchone()
for x in result:
await message.answer(x)
await state.finish()
You could use FSM to get data from user

Discord.py | How to write multiple events with the same name?

Iv'e been trying to create 3 on_raw_reaction_add commands, but only the one positioned last works(doesn't matter which one I put last).
Here's my code:
#client.event
async def on_raw_reaction_add(payload4: discord.RawReactionActionEvent):
message_id = payload4.message_id
if message_id == 921150661456986122:
if payload4.emoji.name == '**':
guild_id = payload4.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
channel = guild.get_channel(921114527075020841)
message = await channel.fetch_message(message_id)
server = message.guild.owner
await server.send(f'''{payload4.member.mention} asked for the ** role.''')
user = client.get_user(payload4.user_id)
emoji = client.get_emoji(767057115306655775)
await message.remove_reaction(emoji, user)
#client.event
async def on_raw_reaction_add(payload3: discord.RawReactionActionEvent):
message_id = payload3.message_id
if payload3.emoji.name == '*':
guild_id = payload3.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
channel = guild.get_channel(921114527075020841)
message = await channel.fetch_message(message_id)
server = message.guild.owner
await server.send(f'''{payload3.member.mention} asked for the * role.''')
user = client.get_user(payload3.user_id)
emoji = client.get_emoji(767057122054635540)
await message.remove_reaction(emoji, user)
#client.event
async def on_raw_reaction_add(payload2: discord.RawReactionActionEvent):
message_id = payload2.message_id
if message_id == 921114830356762666:
guild_id = payload2.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload2.emoji.name == 'vip':
channel = guild.get_channel(921114527075020841)
message = await channel.fetch_message(message_id)
server = message.guild.owner
await server.send(f'''{payload2.member.mention} asked for the vip role.''')
user = client.get_user(payload2.user_id)
emoji = client.get_emoji(767064946919735298)
await message.remove_reaction(emoji, user)
I thought of maybe changing the first 2 events to "bot" and "cord" but it didn't work.
You can't make multiple events, you can though make multiple listeners!
#client.listen('on_raw_reaction_add')
async def my_cool_function(payload: discord.RawReactionActionEvent):
# ... do something
#client.listen('on_raw_reaction_add')
async def my_second_cool_function(payload: discord.RawReactionActionEvent):
# ... do something else
# or
#client.listen()
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
# ... do something
#client.listen()
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
# ... do something else
You can only have a total of 25 listeners.
In python, you can't have multiple functions with the same name, so you can't have multiple events with the same name. As Rose mentioned, if you really want to have the code in different functions, for example because they are in different files, you can use listeners. But if you have these functions in one file, or you hit the limit of 25 listeners, you should add all the code in one function:
#client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
message_id = payload.message_id
if message_id == 921150661456986122:
#add the code that is inside the if in the first function here, but rename payload4 to payload
if payload.emoji.name == '*':
#add the code that is inside the if in the second function here, but rename payload3 to payload
if message_id == 921114830356762666:
#add the code that is inside the if in the third function here, but rename payload2 to payload

How to mention a user without putting id after command in server

#client.command()
async def status(current, content: str):
status = None
for member in current.guild.members:
if str(member.id) == content:
status = member.status
break
if status == discord.Status.online:
online_embed = discord.Embed(
title="awa is online", description="", color=0xF6E5E5
)
await current.send(embed=online_embed)
I would have to do #status [user id] every time, is there a way to make it #status only?
One of the simplest ways to get a member object in a command, allowing you to use a user's id, their name, etc., would be to use the converter they provide.
#client.command()
async def test(current, member: discord.Member=None):
if member == None: # if no member is provided..
member = current.author # ..make member the author
await current.send(f"Hello {member.mention}!")
Other questions like this:
Discord.py get user object from id/tag
Discord.py: How do I get a member object from a user object?

Discord.py How to DM a user from the user ID in a cog even if the user is not in the server I run the command?

I am working on a command that removes a bug, then rewards the user with a bug report token (bugreport)
then dm's them.
So how do I get a User ID even if that user is not in the server that I run this command in?
the code I have for getting and dming the user:
//user is gotten from a query, it is a real ID
userobj = ctx.guild.get_user(user)
dm = await userobj.create_dm()
msg = 'msg'
dm.send(msg)
#commands.command(name='fixbug', allises=['finishbug'],help='[Owner Only] <bugid> <reward?>')
#commands.is_owner()
async def killbug(self, ctx, bugid: int, reward: str = 'False', msg: str = None):
print(bugid)
query = await db.load(
f'''
SELECT * FROM buglogs
WHERE fixedid = {bugid}
''')
print(query)
query = query[0]
await db.query(
f'''
DELETE FROM buglogs
WHERE fixedid = {bugid}
''')
user = query[1]
name = query[3]
log = query[2]
userobj = ctx.guild.get_user(user)
dm = await userobj.create_dm()
if reward == 'True' or reward == 'true' or reward == 'yes':
await self.add_item(user, 'bugreport', 1)
await ctx.send(f'Gave {name} A Bug Report Token, I also squashed \"{log}\" bug!')
await dm.send(f"Thank you for reporting the bug: \"{log}, You have been rewarded 1 Bug Report Token, sell it for your reward!")
else:
await ctx.send('Squashed: {log}')
if msg == None:
dm.send('The bug you reported ({log}) has been resolved, thank you!')
else:
dm.send(msg)
You can use bot.get_user
discordUser = self.bot.get_user(user) #pass user id here
if discordUser is not None:
#do stuff
else:
await ctx.send('user not found')
Warning: this code assumes you are in a cog and have set self.bot = bot in the init like in the docs
References:
get_user

Discord.py bot, category isn't being created at the required position

import discord
from discord.ext import commands
botToken = "*"
client = commands.Bot(command_prefix = '*')
#client.event
async def on_ready():
print("I'm ready!")
#client.command()
async def start(ctx):
a = await ctx.guild.create_category("TEST", position=0)
a.position = 0
client.run(botToken)
position= int and channel.position = int ain't working..Haven't found any question related to my problem, gave bot Administrator permissions at https://discord.com/developers/applications and got the link let him in my server, create a role with everything allowed and gave him the role, didn't work..
create_text_channel and create_voice_channel nothing changes, The channels are being set as if I didn't assign a position to them.
Picture showing where the category position
It's not working because there's no position 0, the first position is always 1
category = await ctx.guild.create_category("TEST", position=1)
If it still creates the category in another position you can manually edit it:
await category.edit(position=1)

Resources