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

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 ='!')

Related

Discord bot cannot fetch channel

I am trying to code a bot that will simultaneously print new messages in a server to console and for the user to be able to send messages to the server at the same time.
import discord
from asyncio import run
from threading import Thread
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
async def p():
ap = await client.fetch_channel(1234567890)
return ap
main_guild = run(p())
def log_msg(msge,date):
with open('log.txt','a') as f:
f.write(msge + '\n' + date)
f.close()
async def send_a_message():
while True:
await main_guild.send(input('Send message: '))
#client.event
async def on_message(message):
base_msg = str(message.author)+': '+str(message.channel.name)+': '+str(message.content)
date = str(message.created_at)
if len(message.attachments) == 0:
print(base_msg)
log_msg(base_msg,date)
return
for i in range(len(message.attachments)):
base_msg += '\n'+(message.attachments[i]).url
log_msg(base_msg,date)
t = Thread(target=lambda:run(send_a_message()))
t.start()
try:
client.run('#######################')
except discord.errors.HTTPException:
from os import system
system('kill 1')
However, I get a strange error:
Traceback (most recent call last):
File "main.py", line 13, in <module>
main_guild = run(p())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "main.py", line 10, in p
ap = await client.fetch_channel(999141783709679668)
File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/client.py", line 1824, in fetch_channel
data = await self.http.get_channel(channel_id)
File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/http.py", line 604, in request
if not self._global_over.is_set():
AttributeError: '_MissingSentinel' object has no attribute 'is_set'
What is causing this and how do I fix this?
Thank you.
To get the channel you are using the client. But you are trying to get the channel before actually running the client, so you can't get the channel.
You have to first run the client and then get the channel. A possibility would be to use the on_ready event (called after client.run('...')) to get the channel.
Here is an example code you can start working with:
import discord
client = discord.Client(intents=discord.Intents.all())
main_guild = None
#client.event
async def on_ready():
global main_guild
await client.wait_until_ready()
main_guild = client.get_channel(1234567890)
print('Connected')
#client.event
async def on_message(message):
if message.author.id == client.user.id: return
if message.channel.type == discord.ChannelType.private: channel = 'DM'
else: channel = message.channel.name
base_msg = f'{message.author}: {channel}: {message.content}'
await main_guild.send(base_msg)
client.run('#######################')

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)

Multiple client request using httpx Runtime Error: Cannot send a request, as the client has been closed

I have the below piece of code
async def get_data(uuid):
async with sema, httpx.AsyncClient(
base_url=udi_data_url, params=params
) as udi_client:
udi_result = udi_client.get(f"/{uuid}")
async with sema, httpx.AsyncClient(
base_url=manufacturer_data_url, params=params
) as client:
manufacturing_result = client.get(f"/{uuid}")
result1, result2 = await asyncio.gather(udi_result, manufacturing_result)
print(result1, result2)
async def main():
await get_data(uuid)
asyncio.run(main())
How do I keep the client connections open as i understand the moment i reach this line
result1, result2 = await asyncio.gather(udi_result, manufacturing_result)
I know that i can do something like
udi_result = await udi_client.get(f"/{uuid}")
and
manufacturing_result = await client.get(f"/{uuid}")
But that's not what I want to do.
I am out of the context and thus
I am getting an error.

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).

I keep getting an error in my discord bot, and cannot figure out how to fix it

I have been trying to help a friend fix his discord bot, but I'm stumped on the solution.
from discord.ext import commands
import bs4
import requests
import time
import lxml
adminkey = "CheeseIsTheBest"
keys = open('keys.txt', 'w')
TOKEN = "token goes here"
client = commands.Bot(command_prefix = "!")
client.remove_command('help')
#client.event
async def on_ready():
print("Locked And Loaded Mr. DarkKnight")
#client.command(name='ping')
async def ping(ctx):
await ctx.send('pong')
#client.command()
async def addkey(ctx, key):
if str(ctx.author) == "ironkey#6969" or str(ctx.author) == "ZERO#2020":
with open('keys.txt', 'r+') as file :
file.write(str(key + "\n"))
file.close()
await ctx.send('key added')
else:
await ctx.send('your not authorized to preform this action ' + str(ctx.author))
#client.command()
async def redeemkey(ctx, key):
with open('keys.txt', 'r+') as file:
for line in file:
if str(key.strip()) == str(line.strip()):
with open('keys.txt', 'w') as file:
keyfile = keyfile.replace(str(key), key + " X")
file.write(keyfile)
file.close()
await ctx.send('key redeemed!')
else:
await ctx.send('This key has already been used')
#client.command()
async def unbind(ctx, *, member):
role = discord.utils.get(ctx.guild.roles, name='authenticated')
await client.remove_roles(member, role)
#client.command(aliases=['inv'])
async def invite(ctx):
await ctx.send('https://discordapp.com/api/oauth2/authorize?client_id=645664026160005129&permissions=8&scope=bot')
#client.command()
async def help(ctx):
embed = discord.Embed(color=discord.Color.dark_blue())
embed.set_author(name="Cheese Auth Help Menu", icon_url="")
embed.add_field(name=".ping", value="a simple fun command! usage : .ping")
embed.add_field(name=".invite", value="also used with the command inv, this command will get you an invite link so you can add this bot to your server! usage: .invite")
await ctx.send(embed=embed)
client.run(TOKEN)
Every time I try to redeem the key I added, I get this error:
Ignoring exception in command redeemkey:
Traceback (most recent call last):
File "C:\Users\seang\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 79,
in wrapped ret = await coro(*args, **kwargs)
File "C:\Users\seang\Downloads\Bot_for_DarkKnight1-_Copy.py", line 41,
in redeemkey keyfile = keyfile.replace(str(key + X))
UnboundLocalError: local variable 'keyfile' referenced before assignment.
From your code i noticed that keyfile.replace is the problem. Variable keyfile is not assigned or declared (defined) yet.You are reading a file line by line in variable line so I think your code should be
keyfile = line.replace(str(key), key + " X")
The error comes from this line:
keyfile = keyfile.replace(str(key), key + " X")
You're trying to make a new value called 'keyfile', but it relies on information which comes from 'keyfile', which doesn't exist yet.

Categories

Resources