Message in a specific Discord channel - python-3.x

Hi guys i'm trying to make the bot send a message automatically in a specific channel. I took the channel ID and pass it in the if condition (a_string.find ('data: []')! = -1). However this code gives me this error. See OUTPU ERROR.
P.S. I'm using Replit and Live is the file name (Live.py)
from discord.ext import commands
from Naked.toolshed.shell import execute_js, muterun_js
import sys
class Live(commands.Cog):
def __init__(self,client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
channel = self.get_channel(828711580434169858)
response = muterun_js('serverJs.js')
original_stdout = sys.stdout # Save a reference to the original standard output
if response.exitcode == 0:
a_string= str(response.stdout)#stampa in console
if (a_string.find('data: []') != -1):
print("Streamer: Offline ")
else:
print("Streamer: Online")
await channel.send('Live Link: https://...link....')
else:
sys.stderr.write(response.stderr)
#commands.command()
async def Live(self,ctx):
await ctx.send('')
def setup(client):
client.add_cog(Live(client))
OUTPUT ERROR:
Ignoring exception in on_ready
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 "/home/runner/Solaris-IA/cogs/Live.py", line 12, in on_ready
channel = self.get_channel(828711580434169858)
AttributeError: 'Live' object has no attribute 'get_channel'

It's self.client.get_channel, not self.get_channel, you haven't defined that function
channel = self.client.get_channel(828711580434169858)

Related

How to edit embed with message id discord bot py in on_ready event

I want to edit a embed in on_ready event this is the only way i can edit can do on_message or is there a way to keep a function running until the program ends?
from discord.ext import commands
import discord
from discord.utils import get
#bot.event
async def on_ready():
msg = bot.get_message(892788147287654471)
em = discord.Embed(title="lik",description="kjk")
await msg.edit(embed=em)
bot.run(os.environ['token'])
error code:
Ignoring exception in on_ready
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 56, in on_ready
msg = bot.get_message(892788147287654471)
AttributeError: 'Bot' object has no attribute 'get_message'
Well as the error says, bot has no get_message attribute. Instead what you can do is get the channel, and then get the message or partial message within.
https://discordpy.readthedocs.io/en/master/api.html?highlight=partial%20message#discord.PartialMessage
Example:
message = bot.get_channel(1234567890).get_partial_message(1234567890)
await message.edit(content="test")

Discord.py Python economy bot with mongodb "NoneType" error

(bad english)
I wanna create a economy bot with mongodb, it worked fine 2 days ago but now I have "NoneType" error
Sorce code from main.py(to add user in db):
#client.event
async def on_ready():
print(f'''
[*]BOT: ON
[*]BOT NAME : {client.user}
[*]BOT ID: {client.user.id}
''')
for guild in client.guilds:
for member in guild.members:
post = {
"_id": member.id,
"balance": 10000000,
"xp": 0,
"level": 1
}
if collection.count_documents({"_id": member.id}) == 0:
collection.insert_one(post)
That code is working because I see that on db
Source code from cog with problem:
class Economic(commands.Cog):
def __init__(self, client):
self.client = client
self.cluster = MongoClient(f"mongodb+srv://discord:{secret}#cluster403.xn9cm.mongodb.net/discord1?retryWrites=true&w=majority")
cluster = MongoClient(f"mongodb+srv://discord:{secret}#cluster403.xn9cm.mongodb.net/users?retryWrites=true&w=majority")
self.collection = cluster.users.tutu
#commands.command(
name = "balance",
aliases = ["ball","money"],
brief = "User balance",
usage = "balance <#user>",
description = "none....."
)
async def user_balace(self, ctx, member: discord.Member = None):
if member is None:
embed = discord.Embed(
title = f"__{ctx.author}__'s balance",
description = f"Money: {self.collection.find_one({'_id': ctx.author.id})['balance']}"
)
await ctx.send(embed=embed)
When I type ">balance" command in console I get that error:
Ignoring exception in command balance:
Traceback (most recent call last):
File "D:\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Nick403\Desktop\Apps\PROJECTS\BOT\cogs\eco.py", line 22, in user_balace
description = f"Money: {self.collection.find_one({'_id': ctx.author.id})['balance']}"
TypeError: 'NoneType' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "D:\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "D:\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: 'NoneType' object is not subscriptable
Can somebody help me ? (sorry for my bad english)
The error message is essentially saying that self.collection.find_one({'_id': ctx.author.id}) is returning as None. In the PyMongo Documentation, we can see that find_one() will return None when no such item is found in the collection. I would rewrite your code to have a safety in the event of not having a specific user in your database.
if self.collection.find({'_id': ctx.author.id}).count() == 0:
self.collection.insert_one({USER OBJECT})
user = self.collection.find_one({'_id': ctx.author.id})

client.(variable) variables in Discord.py Cogs

I am facing an issue while migrating my python code to discord.py.
The issue is, I don't know how to use client. variables in discord.py cogs like client.sniped_messages = {}...
It shows an error -
Traceback (most recent call last):
File "C:\Users\arjun\Documents\Arjun\Python\discord.py\swayde\main.py", line 55, in <module>
client.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\arjun\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Utility' raised an error: NameError: name 'self' is not defined
Here's the code -
import discord
from discord.ext import commands
import random
import datetime
class Utility(commands.Cog):
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}
#commands.Cog.listener()
async def on_message_delete(self,message):
self.client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
#commands.command()
async def snipe(self, ctx):
try:
contents, author, channel_name, time = self.client.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("Couldn't find a message to snipe!")
return
embed = discord.Embed(description=contents, color=discord.Color.purple(), timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
embed.set_footer(text=f"Deleted in : #{channel_name}")
await ctx.channel.send(embed=embed)
def setup(client):
client.add_cog(Utility(client))
Now, when I delete the variable client.sniped_messages = {}, The code runs perfectly.
Please tell me how I can resolve this issue and how to use .client variables in cogs.
Thanks in advance!
You have to indent self.client.sniped_messages = {} so it's inside the __init__ method
def __init__(self, client):
self.client = client
self.client.sniped_messages = {}

discord.py temporary voices

I am making my bot for discord, I want to do this, when a user clicks on a certain voice channel, a new voice channel is created for him, which is deleted upon exit. Here is the code:
import discord
from discord.ext import commands
from discord.utils import get
import asyncio
TOKEN = 'xxxx'
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_voice_state_update(member, before, after):
if after.channel != None:
if after.channel.id == 700246237244555338:
for guild in bot.guilds:
maincategory = discord.utils.get(
guild.categories, id=700246237244555336)
channel2 = guild.create_voice_channel(name=f'канал {member.display_name}', category=maincategory)
await channel2.set_permissions(member, connect=True, mute_members=True, manage_channels=True)
await member.move_to(channel2)
def check(x, y, z):
return len(channel2.members) == 0
await bot.wait_for('voice_state_update', check=check)
await channel2.delete()
# RUN
bot.run(TOKEN)
But i have error...
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "jett.py", line 190, in on_voice_state_update
await member.move_to(channel2)
File "C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\member.py", line 626, in move_to
await self.edit(voice_channel=channel, reason=reason)
File "C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\member.py", line 592, in edit
payload['channel_id'] = vc and vc.id
AttributeError: 'coroutine' object has no attribute 'id'
C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py:340: RuntimeWarning: coroutine 'Guild.create_voice_channel' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Can you help me with this problem or just send me working code for temporary voices
RuntimeWarning: Enable tracemalloc to get the object allocation traceback usually means that you forgot to add an await keyword to an async function. The async function in question is likely create_voice_channel, as the documentation says it is an async function.
To fix this, you'll want to add the await keyword before the function call, similar to this:
channel2 = await guild.create_voice_channel(name=f'канал {member.display_name}', category=maincategory)

Python3 Discord Module No Attribute Client

I was handed a Python Discord Message Mass Prune Script in Py3.
But there were a few errors, Prior to this.
It was working before, but now it's giving me some error that
it didn't give me before.
import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print(' ')
print('Lorem')
print('ipsum')
print('dolor')
print('amet')
print('sit')
print('consectetur')
print('Logged in as:', client.user.name)
print('UID:',client.user.id)
print('Discord version:',discord.__version__)
print('----------')
print('Connected to:')
for server in client.servers:
print(' -',server.name)
# Define commands
#client.event
async def on_ready():
if message.author == client.user:
commands = []
z = 0
for index, a in enumerate(message.content):
if a == " ":
commands.append(message.content[z:index])
z = index+1
commands.append(message.content[z:])
# MASS DELETE OWN MESSAGES
if commands[0] == 'xc':
if len(commands) == 1:
async for msg in client.logs_from(message.channel,limit=9999):
if msg.author == client.user:
try:
await client.delete_message(msg)
except Exception as x:
pass
elif len(commands) == 2:
user_id = ''
for channel in client.private_channels:
if commands[1] in str(channel):
if str(channel.type) == 'private':
user_id = str(channel.id)
async for msg in client.logs_from(discord.Object(id=user_id),limit=9999):
if msg.author == client.user:
try:
await client.delete_message(msg)
except Exception as x:
pass
client.run("TOKEN HERE",bot=False)
Using Py3 Pip, I installed discord and asyncio (The required modules) needed for the script.
At line 4 (client = discord.Client())
It throws off the error
Traceback (most recent call last):
File "discord.py", line 1, in <module>
import discord
File "C:\Program Files\Python36\discord.py", line 4, in <module>
client = discord.Client()
AttributeError: module 'discord' has no attribute 'Client'
Your program is called discord.py. That is masking the real discord module. Call the program something else.
Change your file name from discord.py to another like discord_message.py
AS it is importing discord from your os only

Resources