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
Related
I create a bot that notifies the user at certain times, but from time to time gives this error
dispatcher.py [LINE:390] ERROR | 2022-10-03 04:10:16,846 : Cause exception while getting updates.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.py", line 381, in start_polling
updates = await self.bot.get_updates(
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
result = await self.request(api.Methods.GET_UPDATES, payload)
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 128, in check_result
raise exceptions.TelegramAPIError(description)
aiogram.utils.exceptions.TelegramAPIError: Bad Gateway
I think this problem is on the telegram side itself and is solved via webhook, but I don't want to use them.
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.
I need help with this code since I'm getting an error and I don't know how to fix it. I'm new to coding and I want to learn how to code after I get this problem figured out. I am currently running the code on https://replit.com and I kept on getting this error if your able to figure it out that would be great!
code:
import discord
import os
import colorama
from colorama import Fore, Style
import requests
import time
from colorama import Fore
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
def Cls():
os.system('cls')
Cls()
b = Style.BRIGHT
message = input("What do you want to say in the embed? ")
Cls()
token = "token""
Cls()
b = Style.BRIGHT
print(f"""
{b+Fore.GREEN}
██ ██ ███████ ███ ███ █████ ███████ ███████ ██████ ███ ███
██ ██ ██ ████ ████ ██ ██ ██ ██ ██ ██
████ ████
██ ██ █████ ██ ████ ██ ███████ ███████ ███████ ██ ██ ██ ████ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██
███████ ██ ███████ ██ ██ ██ ██ ███████ ███████ ██████ ██ ██
{b+Fore.BLUE} > {Fore.RESET}MASS DM
{b+Fore.BLUE} > {Fore.RESET}Creator: watch#0001
""")
watch = discord.Client()
#watch.event
async def on_connect():
for user in watch.user.friends:
try:
watchy = discord.Embed(color= discord.Color(0x2f3136))
watchy.set_author(name="join discord.gg/HeKbnh57 ")
watchy.add_field(name="discord.gg/HeKbnh57",value=message)
watchy.set_image(url="https://cdn.discordapp.com/attachments/811724526915289109/830113315405561896/image0.jpg")
time.sleep(.1)
await user.send(embed=watchy)
await user.send("https://www.youtube.com/watch?v=ixyIfsFZGg4")
time.sleep(.1)
print(f'messaged:' + Fore.GREEN + f' {user.name}')
except:
print(f"couldnt message: {user.name}")
print(f"Directed messaged all users friends")
watch.run(token, bot=False)
error:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 300,
in static_login
data = await self.request(Route('GET', '/users/#me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 254,
in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 61, in <module>
watch.run(token, bot=False)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line
723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line
702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line
665,
in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line
511,
in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 304,
in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
First of all the variable token = "token"" should be using the token not "token", also it has an extra ". If you don't wanna use a variable use (in your case) watch.run("token"), with the token beetween the inverted commas, like this: watch.run("1375ioda8da541f7ds984a8asd-ASMSJBNDdasdsKAs").
And you code from watch = discord.Client() to watch.run(token, bot=False) is commented.
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('Отправлено')
I tried to make a simple translate funcion in my Discord Bot and got to this Error:
Ignoring exception in command translate:
Traceback (most recent call last):
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Luca\Documents\Discord\cogs\translate.py", line 30, in translate
await msg.send(embed=new_emd, delete_after=20)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 904, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 156, in request
kwargs['data'] = utils.to_json(kwargs.pop('json'))
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 318, in to_json
return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Translated is not JSON serializable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\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: TypeError: Object of type Translated is not JSON serializable
I already looked it up, but i found no solutions. Because it is in the library i don't know what to do about it. Please help me.
This is the code i wrote:
from googletrans import Translator
import discord
from discord.ext import commands
#commands.command(pass_context=True)
async def translate(self, msg, lang, *,args):
"""Translates words from one language to another.
Usage:
-translate 'language' 'text'
Language example: 'fr' 'en'
"""
#To Check if it has the delete Messages Permission
try:await msg.message.delete()
except:
embed = discord.Embed(
colour=discord.Colour(0x1))
embed.add_field(name="I don't have the permissions to do that!",
value="please give me the 'Manage Messages' permission")
return await msg.send(embed=embed, delete_after=30)
#Simple Translator | Read on the googletrans page
t = Translator(service_urls=['translate.google.com'])
text = t.translate(args, dest=lang)
#Posts Embed with the Text and also the Language
new_emd = discord.Embed(title="Broski Translator in " + lang, description=text, colour=discord.Colour(0x1))
await msg.send(embed=new_emd, delete_after=20)
This seems to be a recurring error in googletrans package.
In this answer by #Maldus you can see a work-around to fix this issue.
Or you can try installing the new alpha version which is supposed to correct this:
pip install googletrans==3.1.0a0