Discord Python Bot Error Message client.command - python

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'])```

Related

Aiogram get error when use ":" in callback data

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

Discord.py ctx.author.id is not woring

So here's my code, some part are messy because im so angry, error message in the end:
from discord.ext import commands
import discord
import random
from keep_alive import keep_alive
import json
import os
import asyncio
#Game variables and list:
bot = commands.Bot(command_prefix='.')
#Game code here:
def o_acc(ctx):
users = await gbd()
if str(ctx.author.id) in users:
return False
else:
users[str(ctx.author.id)] = {}
users[str(ctx.author.id)]["Wallet"] = 10000
with open("user.json", 'w') as f:
json.dump(users, f)
return True
def gbd():
users = json.load(open("user.json", 'r'))
return users
#Check balance command
#bot.command(name='bal')
async def balance(ctx):
await o_acc(ctx.author)
users = await gbd()
em = discord.Embed(title = f"{ctx.message.author.name}'s balance'")
em.add_field(name = 'Wallet balance', value = users[str(ctx.message.author.id)]['wallet'])
await ctx.send(embed = em)
#These commands should be keep in the end!!!!
bot.run('token(bot showing')
Error message:File "main.py", line 32, in balance await o_acc(ctx.author) File "main.py", line 15, in o_acc if str(ctx.author.id) in users: AttributeError: 'Member' object has no attribute 'author'
Just pass in ctx instead of ctx.author as the argument for o_acc().
#Check balance command
#bot.command(name='bal')
async def balance(ctx):
await o_acc(ctx)
users = await gbd()
em = discord.Embed(title = f"{ctx.message.author.name}'s balance'")
em.add_field(name = 'Wallet balance', value = users[str(ctx.message.author.id)]['wallet'])
await ctx.send(embed = em)

Praw blocking subreddits

Hi I'm trying to block a few subreddits in praw like FiftyFifty but I cant find the command for something like that this is also for a discord bot my code is here
#client.command()
async def r(ctx,subred = ""):
subreddit = reddit.subreddit(subred)
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
if not submission.over_18:
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
else:
await ctx.send("NO")
This might be a possible solution
bannedSubreddits = ["FiftyFifty", "various", "other", "subreddits"] #Add as many subreddits as you'd like here or just add one
#client.command()
async def r(ctx,subred = ""):
subreddit = reddit.subreddit(subred)
for bannedSub in bannedSubreddits:
if subreddit == reddit.subreddit(bannedSub): #If a banned subreddit is detected, it sends what you wanted to send when you find an over 18 post
await ctx.send("NO")
return
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
if not submission.over_18:
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
else:
await ctx.send("NO")

How to make Discord.py get how MANY users reacted with a specific emoji?

I'm trying to make a poll command in Discord.py but want at the end the bot to send a list of users that reacted with 1️⃣ and another list of people that reacted with 2️⃣.
This is my code so far:
async def poll(ctx, q1, q2, time : int):
await ctx.send(f"React with 1 to vote for **{q1}** and with 2 to vote for **{q2}**\n**Poll Lasts for {time} seconds**")
poll = discord.Embed(title = "Poll", color = discord.Color.blue())
poll.add_field(name = f"{q1} 1️⃣", value = "᲼᲼᲼᲼᲼᲼")
poll.add_field(name = f"{q2} 2️⃣", value = "᲼᲼᲼᲼᲼᲼")
msg = await ctx.send(embed = poll)
r1 = await msg.add_reaction("1️⃣")
r2 = await msg.add_reaction("2️⃣")
await asyncio.sleep(time)
await ctx.send("Times up! **Poll Closed**")
new_msg = discord.utils.get(client.cached_messages,id = msg.id)
users1 = await r1.reactions[0].users().flatten()
users1.pop(users1.index(client.user))
users2 = await r2.reactions[0].users().flatten()
users2.pop(users2.index(client.user))
em=discord.Embed(title=f'Votes for {q1}', description=" , ".join(user.name for user in users1),color = discord.Colour.blue())
await ctx.send(embed = em)
em=discord.Embed(title=f'Votes for {q2}', description=" , ".join(user.name for user in users2),color = discord.Colour.blue())
await ctx.send(embed = em)
And this is the error I am getting:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'reactions'
Message.add_reaction returns None, you can't use these two lines
r1 = await msg.add_reaction("1️⃣")
r2 = await msg.add_reaction("2️⃣")
Easiest approach would be to fetch the message again with the updated reactions
message = await ctx.send("Whatever")
await message.add_reaction("1️⃣")
await message.add_reaction("2️⃣")
await asyncio.sleep(10)
updated_message = await ctx.channel.fetch_message(message.id)
users1, users2 = [], []
for r in updated_message.reactions:
print(f"{str(r)} was added {r.count} times")
if str(r) == "1️⃣":
users = await r.users().flatten()
users1.extend(users)
elif str(r) == "2️⃣":
users = await r.users().flatten()
users2.extend(users)
# `users1` and `users2` are lists of users that reacted with `1️⃣` and `2️⃣` accordingly
Reference:
Messageable.fetch_message
Message.reactions
Reaction.count
Reaction.users

TypeError: 'NoneType' object is not subscriptable | Python

I am creating a simple USPS Tracking Bot for Discord.
It works by using the !usps TRACKING NUMBER command in Discord
Here is the code:
import shippo
import discord
import asyncio
import datetime
token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
client = discord.Client()
shippo.config.api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
#client.event
async def on_ready():
print('-------------------------')
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('-------------------------')
#client.event
async def on_message(message):
if message.author.bot:
return
if message.content.startswith('!help'):
embed = discord.Embed(title="Help", description="Use `!uSps TRACKING NUMBER` to get started!", color=0x8B4513)
embed.set_author(name="USPS Tracking", url="https://www.usps.com/", icon_url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
embed.set_thumbnail(url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
await message.channel.send(embed=embed)
if message.content.startswith('!'):
cmd = message.content.split()[0].lower()[1:]
args = message.content.split()[1:]
packageTrack = ' '.join(args)
tracking_number = packageTrack
carrier_token = 'usps'
tracking = shippo.Track.get_status(carrier_token, tracking_number)
d1 = datetime.datetime.strptime(tracking['tracking_status']['status_date'], "%Y-%m-%dT%H:%M:%SZ")
new_format = "%m-%d-%Y" + " at " + "%H:%M"
uspsStatus = tracking['tracking_status']['status_details'] + " - " + tracking['tracking_status']['status']
uspsCity = tracking['tracking_status']['location']['city']
uspsState = tracking['tracking_status']['location']['state']
uspsZip = tracking['tracking_status']['location']['zip']
uspsDate = d1.strftime(new_format)
if uspsCity is None:
print("Unavailable")
elif uspsZip is None:
print("Unavailable")
elif uspsState is None:
print("Unavailable")
if cmd == 'usps':
embed = discord.Embed(title="Tracking", color=0x8B4513)
embed.set_author(name="USPS Tracking", url="https://tools.usps.com/go/TrackConfirmAction?tLabels={}".format(str(tracking_number)), icon_url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
embed.set_thumbnail(url="https://www.freepnglogos.com/uploads/usps-png-logo/bridgeport-apartments-usps-png-logo-2.png")
embed.add_field(name="Tracking Number: ", value="{}".format(str(tracking_number)), inline=False)
embed.add_field(name="Status: ", value="{}".format(str(uspsStatus)), inline=False)
embed.add_field(name="Date & Time: ", value="{}".format(str(uspsDate)), inline=False)
embed.add_field(name="Location: ", value="{}".format(str(uspsCity) + ", " + str(uspsState) + " " + str(uspsZip)), inline=False)
await message.channel.send(embed=embed)
client.run(token)
On Line 40 the uspsCity = tracking['tracking_status']['location']['city'] I get the TypeError: 'NoneType' object is not subscriptable error. As you can see I attempted to solve it in the way I thought would work, but it still writes the error. Lists and dicts are still slightly confusing to me so that could be why I'm not getting it.
This Error means you tried to get the elements of nothing (None).
tracking = shippo.Track.get_status(carrier_token, tracking_number)
I guess this function returned None. To avoid this add for example an if statement (try/catch is also possible):
if tracking not None:
uspsStatus = tracking['tracking_status']['status_details'] + " - " + tracking['tracking_status']['status']
uspsCity = tracking['tracking_status']['location']['city']
uspsState = tracking['tracking_status']['location']['state']
uspsZip = tracking['tracking_status']['location']['zip']

Categories

Resources