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

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

Related

Giphy API not responding in discord.py

I made a discord bot that shows you gifs when you type a certain command but the problem is that it works fine in the first half but takes a long time to show the gifs when not used.
Basically it doesn't show the gifs instantly when not used.
Here's the code that I've written:
#client.command()
async def gif(ctx, *, q = 'dance'):
api_key = 'Some Key here'
api_instanc = giphy_client.DefaultApi()
try:
api_responce = api_instanc.gifs_search_get(api_key, q, limit = 7,rating = 'r')
lst = list(api_responce.data)
giff = random.choice(lst)
emb = discord.Embed(title = f"Requested by {ctx.author} " + q )
emb.set_image(url= f'https://media.giphy.com/media/{giff.id}/giphy.gif')
await ctx.channel.send(embed = emb)
except ApiException as e:
await ctx.channel.send("API EXCEPTION")
It doesn't show any errors but doesn't work after the long time.
Any re-write of the code with aiohttp will be appreciated because I am learning that.
I think the module you are using is not asynchronous which leads to blocking read more.
Default in the command is search = None you can use that with an if statement to check.
After that is the request for the api to get the image.
Here is the code edited to use aiohttp
# import aiohttp
# import random
#bot.command()
async def giphy(ctx, search: str = None):
api_key = ""
embed = discord.Embed(title=f"Requested by {ctx.author}")
async with aiohttp.ClientSession() as session:
# search
if search:
embed.description = search
async with session.get(f'http://api.giphy.com/v1/gifs/search?q={search}&api_key={api_key}&limit=10') as response:
data = await response.json()
gif_choice = random.randint(0, 9)
embed.set_image(url=data['data'][gif_choice]['images']['original']['url'])
# radnom
else:
async with session.get(f'http://api.giphy.com/v1/gifs/random?api_key={api_key}&limit=10') as response:
data = await response.json()
embed.set_image(url=data['data']['images']['original']['url'])
await ctx.send(embed=embed)

How to make bot reply to a mention discord.py

I'm making a discord bot and a problem that has come up for me is that the bot won't reply to the user, here is the code
#Code Imports
import discord
import random
from discord import message
from discord import channel
from discord.embeds import Embed
from discord.ext import commands
from discord.ext.commands.bot import Bot
from discord.message import Message
from apikeys import *
from discord import guild
from discord import emoji
from discord import *
from discord import ContentFilter
from discord import channel
from discord import client
#intents
intents=discord.Intents.default()
intents.members=True
#prefix
client=commands.Bot(command_prefix='!',intents=intents)
#Start
#client.event
async def on_ready():
for emoji in client.emojis:
print("Name:", emoji.name + ",", "ID:", emoji.id)
print('Bot is Online {0.user}'.format(client))
print("--------------------------------------------------------------------------------------------------------------------------------------------------------")
client.remove_command('help')
#Commands
#client.command()
async def work(ctx):
await ctx.send('use !war to get up the war menu')
emojigood = '\N{THUMBS UP SIGN}'
emojibad="\N{THUMBS DOWN SIGN}"
#client.command()
async def help(ctx):
embed=discord.Embed(title='Help', description='!war is currently under testing please do not complain about it', color=0x00000)
await ctx.send(embed=embed)
#client.command()
async def war(ctx):
embed = discord.Embed(title='War', description='You are starting a war, do you want to continue?', color=0x00000)
msg = await ctx.send(embed=embed)
await msg.add_reaction(emojigood)
await msg.add_reaction(emojibad)
def check(r, user):
return (r.emoji == emojigood or r.emoji == emojibad) and r.message == msg
#Checks whether the message is the same, and the emoji is one of the accepted ones, and returns either True or False
r, user = await client.wait_for('reaction_add',timeout=10 ,check=check)
#this is equivalent to a event listener within your command, it will stop there until a reaction that meets the requirements has been found
#(This won't block other commands and functions)
if r.emoji == emojigood:
embed = discord.Embed(title='War', description='Please now choose a country', color=0x00000)
await ctx.send(embed=embed)
prefix = "!" #insert your prefix
async def on_message(message):
if message.author == client.user:
return
if message.content == f'{prefix}war': #dont need to use this string, just illustrating the point
await message.channel.send("What country do you want to start a war with?")
def check(msg):
return msg.author == message.author and len(msg.role_mentions) > 0
msg = await client.wait_for('message', check=check)
role = msg.role_mentions[0]
channel = client.get_channel(849230881994047508)
await channel.send(f"{role.mention} {message.author} has declared war on you.")
client.run(token)
What's meant to happen:
Bot: Which role would you like to start a war with
User:#something
Bot:Send information to UN, 'War on #something'
I don't know how to make it see the role mention
You have a couple of issues, the way to make the code you're using function decently is to replace message.content with message.clean_content, however, 1. That will react to any message starting with # or a mention, which is probably not what you want, and 2. any message not beginning with the mention wouldn't work.
You say in your description that you're looking for role mentions, which is a different attribute, and you're looking to send a message, and wait for a response, so here's a piece of sample code that would solve those issues, assuming I'm interpreting your question correctly:
def check(msg):
return msg.author == message.author and len(msg.role_mentions) > 0
msg = await client.wait_for('message', check=check)
role = msg.role_mentions[0]
channel = client.get_channel(ID of the channel)
await channel.send(f"{role.mention} {message.author} has declared war on you."
If I misinterpreted any of what you wanted or you're not sure how some of it works, shoot me a comment and I'll do my best to explain!
Docs reference for slightly more complex objects used:
role_mentions,
wait_for(),

Discord.py Bot is not online, but still works

i have a problem with my discord bot, whenever i run the code below using apraw to get the titles of the recent submissions on a subreddit the bot doesn't appear online anymore but still returns the titles in CMD :
Bot is not online when i execute this but still asks for subreddit name & prints the titles of the new posts of the subreddit in CMD:
import asyncio
import apraw
from discord.ext import commands
bot = commands.Bot(command_prefix = '?')
#bot.event
async def on_ready():
print('Bot is ready')
await bot.change_presence(status=discord.Status.online, activity=discord.Game('?'))
#bot.command()
async def online (ctx):
await ctx.send('Bot is online !')
reddit = apraw.Reddit(client_id = "CLIENT_ID",
client_secret = "CLIENT_SECRET",
password = "PASSWORD",
user_agent = "pythonpraw",
username = "LittleBigOwl")
#bot.event
async def scan_posts():
xsub = str(input('Enter subreddit name : '))
subreddit = await reddit.subreddit(xsub)
async for submission in subreddit.new.stream():
print(submission.title)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(scan_posts())
bot.run('TOKEN')
But is online when i execute this but obviously doesn't ask for sub name... :
import asyncio
import apraw
from discord.ext import commands
bot = commands.Bot(command_prefix = '?')
#bot.event
async def on_ready():
print('Bot is ready')
await bot.change_presence(status=discord.Status.online, activity=discord.Game('?'))
#bot.command()
async def online (ctx):
await ctx.send('Bot is online !')
bot.run('TOKEN')
So reddit is the problem here. But what exaclty do i ahve to change in order to make my bot apear online whilst still being able to retreive the titles of new submissions on a given subreddit? The code doesn't return any error:/
the #bot.event that you put above async def scan_posts(): should be changed to #bot.command(). It triggers by itself because you have this in your code:
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(scan_posts())
this is what causes the scan_posts to run automatically. You should remove this as you want scan_posts to be a bot command and not something that happens automatically. The bot also doesn't come online because of this code. What this does is check if this file has been run and then runs scan_posts. The rest of the code won't be triggered.
Also, you shouldn't change presence in on_ready as Discord has a high chance to completely disconnect you during the on_ready event and there is nothing you can do to prevent it. Instead you can use the activity and status kwargs in commands.Bot like:
bot = commands.Bot(command_prefix = '?', status=discord.Status.online, activity=discord.Game('?'))

name 'user' is not defined mentions

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

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