Discord bot with wolfram alpha api not working - python

So I'm making a discord bot that uses the wolfram alpha api to answer questions. I am using the wolframalpha module in python and this is my code:
import discord
import wolframalpha
bot = discord.Client()
token = "XXX"
app_id = "XXX"
client = wolframalpha.Client(app_id)
#bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
#bot.event
async def on_message(msg):
if(not msg.content.startswith("w,")):
return
question = msg.content[2:len(msg.content)]
res = client.query(question)
em = discord.Embed(title=str(msg.author), description = next(res.results).text)
await msg.channel.send(embed=em)
bot.run(token)
It is intended to respond to discord messages of the form w, question. For example w, how many inches in a foot?. And I want it to reply with an embed.
But when I run it, it shows this error:
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 19, in on_message
res = client.query(question)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/wolframalpha/__init__.py", line 127, in query
doc = xmltodict.parse(resp, postprocessor=Document.make
Logged in as Paradøx#3063
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 21, in on_message
res = client.query(question)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/wolframalpha/__init__.py", line 127, in query
doc = xmltodict.parse(resp, postprocessor=Document.make)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/xmltodict.py", line 325, in parse
parser.ParseFile(xml_input)
File "../Modules/pyexpat.c", line 461, in EndElement
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/xmltodict.py", line 141, in endElement
self.item = self.push_data(self.item, name, item)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/xmltodict.py", line 157, in push_data
result = self.postprocessor(self.path, key, data)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/wolframalpha/__init__.py", line 174, in make
value = cls._find_cls(key)(value)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/wolframalpha/__init__.py", line 134, in __init__
self._handle_error()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/wolframalpha/__init__.py", line 141, in _handle_error
raise Exception(template.format(**self))
Exception: Error 1: Invalid appid
Since it says invalid appid at the end I rechecked the app id and it was correct.

Related

Discord.py: Slash command interaction error

I am using Pycord
The code below is the slash command I am using.
class slashcommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.slash_command(
guild_ids = testingservers,
name = "prefix",
description = "check which prefix on this server")
async def prefix(self, ctx):
with open('Source\\prefixes\\prefixs.json', 'r') as f:
prefixes = json.load(f)
try: prefix = prefixes[str(ctx.guild.id)]
except KeyError:
prefix = "_"
await ctx.respond(f"This Server prefix is : ``{prefix}``")
Below is an error when using the slash command above.
Ignoring exception in on_interaction
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 738, in process_application_commands
command = self._application_commands[interaction.data["id"]]
KeyError: '969961755574947870'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 1048, in on_interaction
await self.process_application_commands(interaction)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 755, in process_application_commands
await self.sync_commands(unregister_guilds=[guild_id])
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 693, in sync_commands
await self.http.bulk_upsert_command_permissions(
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 338, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
Idk why causes that.
Its worked before.
Please tell me how to fix that.

Embed not being sent

import discord
from discord.ext import commands
import random
import praw
cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
client_secret = "",
username = "",
password = "",
user_agent = "")
#cl.event
async def on_ready():
print("Bot is ready, get ready to do wutever u want with it")
#cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
all_submission = []
subreddit = reddit.subreddit("subr")
subs = subreddit.filter(limit = amount)
for submission in subs:
all_submission.append(submission)
random_sub = random.choice(all_submission)
name = random_sub.title
url = random_sub.url
em = discord.embed(title = name)
em.set_image = url
await ctx.send(embed=em)
print("embed sent")
cl.run("")
when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 20, in meme
subs = subreddit.filter(limit = amount)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
self._fetch()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
data = self._fetch_data()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
return self._reddit.request("GET", path, params)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
return self._core.request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
return self._request_with_retries(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
self._request_token(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request
This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed
This doesn't appear to be a discord.py issue, it appears to be related to the praw 0auth flow.
According to the traceback, there's an authentication issue in your praw credentials. Double, triple, and quadruple check your authentication credentials and flow with the workflow and methodology in the docs

async and threading and getting channel and sending a message to channel discord.py Python

I'm trying to create a feature where users get notified when its their birthday. I've been at this for weeks but can't seem to find the error.
The problem is that I keep getting an error of:
"Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "main.py", line 59, in check_for_birthdays
await channel.send("Hey Everyone, Let's wish <#" + cord_user_id + "> Happy Birthday!!!")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/aiohttp/client.py", line 1117, in __aenter__
self._resp = await self._coro
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/aiohttp/client.py", line 448, in _request
with timer:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/aiohttp/helpers.py", line 635, in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task"
I keep trying different things such as await asyncio.sleep(time_to_sleep) and try to get_channel() but still get errors.
The code:
async def check_for_birthdays(time_to_sleep):
while True:
from datetime import datetime
from pytz import timezone
tz = timezone('EST')
obj = datetime.now(tz)
string = str(obj).split()[1]
index = string.index(":")
hour = int(string[:index]) + 1
# user = await client.fetch_user(user_id)
# user.send("hello user, some message to user")
# if hour != (9):
# # await channel.send("checking birthdays, not 9am currently.")
# await asyncio.sleep(time_to_sleep)
# continue
# await user.send("9am check successful.")
lst_of_users_today = is_anyones_birthday()
server_id = some_server_id
guild = client.get_guild(server_id)
channel_id = some_channel_id
channel = guild.get_channel(channel_id)
for cord_user_id in lst_of_users_today:
await channel.send("Hey Everyone, Let's wish <#" + cord_user_id + "> Happy Birthday!!!")
time.sleep(time_to_sleep)
import asyncio
threading.Thread(target=asyncio.run, args=(check_for_birthdays(THIRTY_MINUTES*2),)).start()
If you have any suggestions to solve this problem another way, I'm open to suggestions. Basically, allow discord bot to run as normal without being interrupted and check on a specific hour every day if there is a birthday match, for which it shall notify them in the discord channel.

'NoneType' object has no attribute 'group' - how to handle it?

I'm trying to use Python to implement a Discord bot, mainly using the Google Translate API. The bot.py source file looks like this:
from dotenv import load_dotenv
from googletrans import Translator
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
bot = commands.Bot(command_prefix=('!', '$', '#', '.'))
#bot.command()
async def translate(ctx, firstlang, secondlang, word):
translator = Translator()
result = translator.translate(word, dest=secondlang, src=firstlang)
await ctx.send(f'```The translation of your word/phrase is: {result}```')
bot.run(TOKEN)
However, when I try running
$translate en es door
on my server I get
Ignoring exception in command translate:
Traceback (most recent call last):
File "/home/aurinko/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 44, in translate
result = translator.translate(word, dest=secondlang, src=firstlang)
File "/home/aurinko/lib/python3.8/site-packages/googletrans/client.py", line 182, in translate
data = self._translate(text, dest, src, kwargs)
File "/home/aurinko/lib/python3.8/site-packages/googletrans/client.py", line 78, in _translate
token = self.token_acquirer.do(text)
File "/home/aurinko/lib/python3.8/site-packages/googletrans/gtoken.py", line 194, in do
self._update()
File "/home/aurinko/lib/python3.8/site-packages/googletrans/gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/aurinko/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/aurinko/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/aurinko/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'group'
how would you go about this? Any help is appreciated

It doesn’t send a message in a DM with 'discord.py'

My code:
a = 1
b = 600
#client.command()
async def iponergoopelda(ctx):
for line in range(a, b):
with open("id users2.txt") as f:
data = f.readlines()
for line in data:
user = await client.fetch_user(int(line.strip()))
await user.send('hey')
print('Отправлено')
This doesn’t a send message in a DM because the error with a DM,
Ignoring exception in command iponergoopelda:
Traceback (most recent call last):
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Никитос\Desktop\Nukebot.py", line 51, in iponergoopelda
await user.send('hey https://discord.com/api/oauth2/authorize?client_id=815193692432367646&permissions=2214068032&scope=bot')
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\abc.py", line 883, in send
channel = await self._get_channel()
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\user.py", line 697, in _get_channel
ch = await self.create_dm()
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\user.py", line 725, in create_dm
data = await state.http.start_private_message(self.id)
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 247, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Никитос\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
In the document I have ids for people. I tried to get it to work with three ids, but with 200 ids it doesn’t work.
How can I do it? Maybe try and except?
The user simply has the dm's disabled, and there isn't any way of sending the message then. You can put a try/except block:
a = 1
b = 600
#client.command()
async def iponergoopelda(ctx):
for line in range(a , b):
with open("id users2.txt") as f:
data = f.readlines()
for line in data:
user = await client.fetch_user(int(line.strip()))
try:
await user.send('hey')
except:
pass
print('Отправлено')

Categories

Resources