Aiogram get error when use ":" in callback data - python

my code:
#dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
builder = InlineKeyboardMarkup()
response = await get_faq()
for i in response:
builder.add(types.InlineKeyboardButton(
text=f"{i.get('title')}",
callback_data = faq_callback.new(action='faqAct' ,id=i.get('id'), text=str(":")))
)
await message.reply(
"Выберите тот блок который соответствуе вашему запросу"
, reply_markup=builder)
error:
Symbol ':' is defined as the separator and can't be used in parts' values

Related

Update an embed message that already exists in Discord

I want to update an embed message that my bot has already written in a specific channel, how can I do that? If i try to use message.edit it givesthis error: discord.errors.Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
import discord
import json
from discord.ext import commands
def write_json(data,filename="handle.json"):
with open (filename, "w") as f:
json.dump(data,f,indent=4)
class Handle(commands.Cog):
def __init__(self, client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
print("Modulo_Handle: ON")
#commands.command()
async def Handlers(self,ctx):
with open('handle.json','r') as file:
data = json.load(file)
embed = discord.Embed.from_dict(data)
await ctx.channel.send(embed=embed)
file.close()
#commands.Cog.listener()
async def on_message(self, message):
if str(message.channel) == "solaris™-handle":
author = message.author
content = message.content
user = str(author)
with open ("handle.json") as file:
data = json.load(file)
temp = data['fields']
y={"name":user[:-5],"value":content}
temp.append(y)
write_json(data)
updated_embed = discord.Embed.from_dict(data)
await message.edit(embed=updated_embed)
file.close()
def setup(client):
client.add_cog(Handle(client))
msg_id = 875774528062640149
channel = self.client.get_channel(875764672639422555)
msg = await channel.fetch_message(msg_id)
with open('handle.json','r') as file:
data = json.load(file)
embed = discord.Embed.from_dict(data)
await msg.edit(embed=embed)
Fixed adding this code below write_json(data) and remove
updated_embed = discord.Embed.from_dict(data) await message.edit(embed=updated_embed)

Discord Python Bot Error Message client.command

I've tried modifying the client value, but I am still getting the same error, which is attached below.
This is the code for a weather discord bot:
import discord
import os
import requests
import json
from discord.ext import commands
client = discord.Client()
api_key = "12345"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
#client.command()
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message.channel
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_temperature_celsiuis = str(round(current_temperature - 273.15))
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
embed = discord.Embed(
title=f"Weather forecast - {city_name}",
color=0x7289DA,
timestamp=ctx.message.created_at,
)
embed.add_field(
name="Description",
value=f"**{weather_description}**",
inline=False)
embed.add_field(
name="Temperature(C)",
value=f"**{current_temperature_celsiuis}°C**",
inline=False)
embed.add_field(
name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(
name="Atmospheric Pressure(hPa)",
value=f"**{current_pressure}hPa**",
inline=False)
embed.set_footer(text=f"Requested by {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send(
f"There was no results about this place!")
client.run(os.environ['TOKEN'])
Error:
Traceback (most recent call last):
File "main.py", line 135, in <module>
#client.command()
AttributeError: 'Client' object has no attribute 'command'
New to discord bots. I am unable to fix this issue.
Any feedback would be appreciated...........................
write something like that: client = command.Bot(command_prefix="!") instade of client = discord.Client()
import discord
import os
import requests
import json
from discord.ext import commands
client = command.Bot(command_prefix="!")
api_key = "12345"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
#client.command()
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message.channel
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_temperature_celsiuis = str(round(current_temperature - 273.15))
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
embed = discord.Embed(
title=f"Weather forecast - {city_name}",
color=0x7289DA,
timestamp=ctx.message.created_at,
)
embed.add_field(
name="Description",
value=f"**{weather_description}**",
inline=False)
embed.add_field(
name="Temperature(C)",
value=f"**{current_temperature_celsiuis}°C**",
inline=False)
embed.add_field(
name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(
name="Atmospheric Pressure(hPa)",
value=f"**{current_pressure}hPa**",
inline=False)
embed.set_footer(text=f"Requested by {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send(
f"There was no results about this place!")
client.run(os.environ['TOKEN'])```

try make discord bot, but why client.send() error?

import discord
import requests
import asyncio
from json import loads
twitch_Client_ID = 'id'
twitch_Client_secret = 'secret'
discord_Token = 'token'
discord_channelID = 'id'
discord_bot_state = 'TEST'
twitchID = 'tid'
msg = 'LIVE! https://www.twitch.tv/' + twitchID
client = discord.Client()
#client.event
async def on_ready():
print(client.user.id)
print("ready")
game = discord.Game(discord_bot_state)
await client.change_presence(status=discord.Status.online, activity=game)
channel = client.get_channel(int(discord_channelID))
oauth_key = requests.post("https://id.twitch.tv/oauth2/token?client_id=" + twitch_Client_ID +
"&client_secret=" + twitch_Client_secret + "&grant_type=client_credentials")
access_token = loads(oauth_key.text)["access_token"]
token_type = 'Bearer '
authorization = token_type + access_token
print(authorization)
check = False
while True:
print("ready on Notification")
headers = {'client-id': twitch_Client_ID,
'Authorization': authorization}
response_channel = requests.get(
'https://api.twitch.tv/helix/streams?user_login=' + twitchID, headers=headers)
print(response_channel.text)
# try:
if loads(response_channel.text)['data'][0]['type'] == 'live' and check == False:
await client.wait_until_ready()
await channel.send(msg)
print("Online")
check = True
# except:
# print("Offline")
#check = False
await asyncio.sleep(10)
client.run(discord_Token)
here my all code..
and
i saw this error
AttributeError: 'NoneType' object has no attribute 'send'
# try:
if loads(response_channel.text)['data'][0]['type'] == 'live' and check == False:
await client.wait_until_ready()
await channel.send(msg)
I think the problematic code is here.
what's wrong here?
why always error.....
i try
this: https://www.reddit.com/r/discordapp/comments/6ylp7t/python_bot_channel_object_has_no_attribute_send/
and this:
AttributeError: 'NoneType' object has no attribute 'send' Discord.py rewrite
but do not work for me !
Looks like your channel is None. According to the docs get_channel(id: int) might return None when channel has not been found. Double check your discord_channelID is correct and that it is an int (not str as in your example).

Is there anyway to make PRAW faster for discord.py

This works and I have no issue with it. my bot is about 1100 lines of code so not that much. I have a standard meme command using PRAW. Is there any way to make its response time faster and not embedding it is not an option. My ms is average.
code:
#client.command(pass_context=True)
async def meme(ctx):
subreddit = reddit.subreddit("meme")
all_subs = []
top = subreddit.top(limit=50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(title = name)
embed.set_image(url=url)
await ctx.send(embed=embed)
You can store a meme and then send it later. By sending and then getting a meme, you do not have to wait to get a meme before sending one. Then you prepare for the next one.
#client.command(pass_context=True)
async def meme(ctx):
if not hasattr(client, 'nextMeme'):
client.nextMeme = getMeme()
name, url = client.nextMeme
embed = discord.Embed(title = name)
embed.set_image(url=url)
await ctx.send(embed=embed)
client.nextMeme = getMeme()
def getMeme():
subreddit = reddit.subreddit("meme")
top = subreddit.top(limit=50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
return name, url
I changed bot to client, if client does not work for you then replace it with bot.

message.channel.send doesn't send message [discord.py]

import discord
from discord.ext import commands, tasks
import datetime
import requests
import time
from bs4 import BeautifulSoup
client = discord.Client()
r = requests.get("https://www.worldometers.info/coronavirus/country/italy/")
s = BeautifulSoup(r.text, "html.parser")
data = s.find_all("div",class_ = "maincounter-number")
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#tasks.loop(seconds=50.0)
async def covid():
x = datetime.datetime.now()
d = x.strftime("%M")
if d == "21":
channel = bot.get_guild(guild).get_channel(channel)
await message.channel.send("casi di coronavirus in italia: \ncasi totali: " +
data[0].text.strip()
+ "\nmorti totali: " + data[1].text.strip()
+ "\nguariti totali: " + data[2].text.strip())
#covid.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
#covid.after_loop
async def post_loop(self):
if self.covid.failed():
import traceback
error = self.covid.get_task().exception()
traceback.print_exception(type(error), error, error.__traceback__)
client.run('token)
basically this code checks if it is a specified time and if it is it sends a message with the covid data of italy but it doesn't work and doesn't return anything i tried even adding an error handler (traceback) and doesn't do anything the only output i have is from async def on_ready()
so i tried this:
data = ''
#tasks.loop(seconds=50.0)
async def covid(ctx):
global data
x = datetime.datetime.now()
d = x.strftime("%M")
if d == "21":
data = "casi di coronavirus in italia: \ncasi totali: " +
data[0].text.strip() + "\nmorti totali: " + data[1].text.strip()
return data
#covid.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
#client.command()
async def get_covid(ctx):
global data
await ctx.send(data)
but i don't get any output and if i add #client.command() before async def covid
it gives me this error:
Traceback (most recent call last):
File "C:\Users\danie\OneDrive\Desktop\test.py", line 26, in
async def covid(ctx):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site- packages\discord\ext\commands\core.py", line 1162, in decorator
result = command(*args, **kwargs)(func)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1317, in decorator
return cls(func, name=name, **attrs)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site- packages\discord\ext\commands\core.py", line 210, in init
raise TypeError('Callback must be a coroutine.')
TypeError: Callback must be a coroutine.
>>>
You need to add a context in the function and #bot.command() decorator followed by your instance.
Likewise:
#client.command()
async def test(ctx):
await ctx.send('PASSED')
a message is an event and you need to add a proper listener for it to work. You don't need to use this event unless you need the text data.
In your case, you are sending the data directly from your COVID-19 function which doesn't do anything since the message is not defined.
It would be as:
#STORE THE VALUE OF COVID INSIDE DATA VARIABLE.
data = ''
#tasks.loop(seconds=50.0)
async def covid():
global data
x = datetime.datetime.now()
d = x.strftime("%M")
if d == "21":
#Assign the value to DATA VARIABLE.
data = "casi di coronavirus in italia: \ncasi totali: " + data[0].text.strip() + "\nmorti totali: " + data[1].text.strip()
#Return the MODIFIED Data
return data
Now send the data with this function.
#client.command()
async def get_covid(ctx):
global data
await ctx.send(data)
Also, You defined the client wrongly. client = discord.Client()
It should be as:
# change '!' to any prefix you would like to use.
client = commands.Bot(command_prefix ='!')

Categories

Resources