I need assistantance with this python code - python

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.

Related

What could be causing this error: RuntimeError('Event loop is closed') in Python

I am creating a discord bot in pyCharm. This is the following code I have:
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
client.run(TOKEN)
When I run it the following errors are produced:
Traceback (most recent call last):
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\elrod\venv\lib\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 "C:\Users\elrod\OneDrive\Desktop\Assignments\CPSC\Python\HextchLibraryApp\HextechLibrary.py", line 25, in <module>
client.run(TOKEN)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\elrod\venv\lib\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.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022950CEF160>
Traceback (most recent call last):
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Process finished with exit code 1
Now, what I find interesting is this:
I can assure you that I have a .env file set up as such:
DISCORD_TOKEN={my-token-here}
DISCORD_GUILD={my-server-here}
and it is the correct information
I know this because when I take the same token out of the .env file and just paste it directly into client.run() it works without issue, but of course this is private information!
So, the issue is that my file isnt being read properly? I would disagree because in testing I find that the string in DISCORD_GUILD is being read in properly without issue
I also tried the ole turn it off and back on trick by resetting to a new token but no luck
This is my last resort to understanding this error. Does anyone know what could be causing this error and ho to fix it?
Your .env file should look like this:
# .env
DISCORD_TOKEN = ADASIUHFOAka12312jsdfhpAFDA.GnTdIh.dOU0fjmz-WhfDebLN7x8ncuGbLVWyPXNftirGA
Should not contain the {}, if you included them (taking literally as you wrote in your question).
Also, you should set your intents under Discord Developers - Applications and declare them when defining client.

RuntimeError: Event loop is closed (discord.py)

So I was making discord bot and everything seemed to be successful, until I stopped programm and started getting this error (yes... kinda big):
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\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 "C:\Users\user\PycharmProjects\DsBots\bot.py", line 30, in <module>
client.run(TOKEN)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\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.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000026E2673BD90>
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
So I found out that the problem is in authorization, and maybe security, or maybe an error in code causes bot to logout().
I found many same questions, but many of them was asked because of undetected syntax error.
Any suggestions?...
Edit: Sorry, forgot to post code. Here it is:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
client = discord.Client()
#client.event
async def on_ready():
# print(f'{client.user} has connected to Discord!')
guild = discord.utils.get(client.guilds, name=GUILD)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
async def on_message(message):
print(message)
client.run(TOKEN)
So the problem was because I was writting my TOKEN and GUILD in .env file in {}/"" (so it looked like DISCORD_TOKEN="token" or DISCORD_TOKEN={token}). But .env file always writes variables in string type. I didn't knew that, so I was getting LoginFailure: Improper token has been passed. (thanks to Eric Jin) because of my TOKEN and GUILD was with {}.
The problem solution was very simple:
Old code (.env file):
DISCORD_TOKEN="token"
DISCORD_GUILD="guild"
New code:
DISCORD_TOKEN=token
DISCORD_GUILD=guild
(yes...)

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.

Python script to download all the media from a Telegram Channel using Telethon

I was trying to use Telethon but turns out is really slow
So I tried using this gist as suggested in
this post
I have the following errors . Can anyone please help me?
Here is my code:
from telethon.sync import TelegramClient
from FastTelethon import download_file
import os
import asyncio
async def getAllMediaFromchannel():
os.chdir("/home/gtxtreme/Documents/McHumour")
api_hash = "<hidden>"
api_id = <hidden>
client = TelegramClient('MCHumour', api_id, api_hash)
client.start()
ch_entity = await client.get_entity("telegram.me/joinchat/AAAAAEXnb4jK7xyU1SfAsw")
messages = client.iter_messages(ch_entity, limit=50)
def progress_cb(current, total):
print('Uploaded', current, 'out of', total,
'bytes: {:.5%}'.format(current / total))
async for msg in messages:
result = await download_file(client, msg.document, "/home/gtxtreme/Documents/McHumour",
progress_callback=progress_cb)
print("*************************\nFile named {0} saved to {1} successfully\n********************".format(
msg.message, result))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(getAllMediaFromchannel())
Here is my error
[gtxtreme#archlinux ~]$ python PycharmProjects/python_gtxtreme/tgBotrev1.py
PycharmProjects/python_gtxtreme/tgBotrev1.py:13: RuntimeWarning: coroutine 'AuthMethods._start' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "PycharmProjects/python_gtxtreme/tgBotrev1.py", line 31, in <module>
loop.run_until_complete(getAllMediaFromchannel())
File "/usr/lib/python3.8/asyncio/base_events.py", line 612, in run_until_complete
return future.result()
File "PycharmProjects/python_gtxtreme/tgBotrev1.py", line 14, in getAllMediaFromchannel
ch_entity = await client.get_entity("telegram.me/joinchat/AAAAAEXnb4jK7xyU1SfAsw")
File "/usr/lib/python3.8/site-packages/telethon/client/users.py", line 310, in get_entity
result.append(await self._get_entity_from_string(x))
File "/usr/lib/python3.8/site-packages/telethon/client/users.py", line 512, in _get_entity_from_string
invite = await self(
File "/usr/lib/python3.8/site-packages/telethon/client/users.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "/usr/lib/python3.8/site-packages/telethon/client/users.py", line 56, in _call
future = sender.send(request, ordered=ordered)
File "/usr/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 170, in send
raise ConnectionError('Cannot send requests while disconnected')
ConnectionError: Cannot send requests while disconnected
[gtxtreme#archlinux ~]$
Also any other suitable way of doing it would be preferred
client.start is an async method so you should await it.
it only needs the await if it is inside a function. if you call it outside of a function telethon adds the await implicitly for convenience

Categories

Resources