Unable to import main in discord.py - python

I have a little problem which you can skip and does not give you a big error that doesn't let you run the bot, by it is very frustrating tho.
Code:
import asyncio
import discord
from discord.ext import commands
from main import db
^^^^ Unable to import 'main' [pylint(import-error)]
import datetime
import random
I am using cogs so that's why I am importing from main.

If you are using cogs you don't have to import main. Just give a look to the discord.py docs and you will see that cogs must be like this:
import discord
from discord.ext import commands
class MembersCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
#commands.guild_only()
async def joined(self, ctx, *, member: discord.Member):
"""Says when a member joined."""
await ctx.send(f'{member.display_name} joined on {member.joined_at}')
#commands.command(name='coolbot')
async def cool_bot(self, ctx):
"""Is the bot cool?"""
await ctx.send('This bot is cool. :)')
#commands.command(name='top_role', aliases=['toprole'])
#commands.guild_only()
async def show_toprole(self, ctx, *, member: discord.Member=None):
"""Simple command which shows the members Top Role."""
if member is None:
member = ctx.author
await ctx.send(f'The top role for {member.display_name} is {member.top_role.name}')
def setup(bot):
bot.add_cog(MembersCog(bot))
And in main.py: bot.load_extension('folder_name.file_name')
This is just an example.

Related

nextcord.ext.commands.errors.CommandNotFound: Command "roles" is not found

Problem : nextcord.ext.commands.errors.CommandNotFound: Command
"roles" is not found
cog.py file:
from nextcord.ext import commands
from button_roles.role_view import RoleView
class ButtonRoles(commands.Cog, name="Board Roles"):
def __init__(self, bot: commands.Bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(RoleView())
#commands.command()
#commands.is_owner()
async def roles(self, ctx: commands.Context):
await ctx.send("Click a button to add or remove a role.", view=RoleView())
def setup(bot: commands.Bot):
bot.add_cog(ButtonRoles(bot))
role_view.py file:
import nextcord
from bot import custom_id
import config
VIEW_NAME = "RoleView"
class RoleView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
#nextcord.ui.button(label="NSFW", emoji=":dart:", style=nextcord.ButtonStyle.primary, custom_id=custom_id(VIEW_NAME, config.NSFW_ROLE_ID))
async def nsfw_button(self, button, interaction):
interaction.response.send_message("Ты получил NSFW роль")
bot.py file
from code import interact
from unicodedata import name
from nextcord.ext import commands
import config
import os
import nextcord
import textwrap
import requests, json, random, datetime, asyncio
from PIL import Image, ImageFont, ImageDraw
from nextcord import File, ButtonStyle, Interaction, ChannelType, SlashOption
from nextcord.ui import Button, View
from nextcord.abc import GuildChannel
from dotenv import load_dotenv
load_dotenv()
intents = nextcord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=config.PREFIX, intents=intents)
serverID = config.GUILD_ID
BOT_NAME = config.BOT_NAME
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
#bot.slash_command(name="add", guild_ids = [serverID])
async def add(ctx, left: int, right: int):
"""Слаживать левое и правое число"""
await ctx.send(left + right)
#bot.slash_command(name="splx", guild_ids = [serverID])
async def _bot(ctx):
"""Вся инфа"""
await ctx.send("Читается как Суплекс а не спликс")
def custom_id(view: str, id: int) -> str:
return f"{config.BOT_NAME}:{view}:{id}"
if __name__ == '__main__':
bot.run(os.getenv("DISCORD_TOKEN"))
Bot successfully running without problems, and others commands running also without mistakes, however instead of $roles one
I need to know how to make a bot able to react to a trigger $roles, thanks (i'm new in discord bots developing so sorry bcs of my stupism)
well, the commands was indented incorrectly in the cog file.
you should make the commands defined in the cog file in the cog defination, like this:
class ABC(commands.Cog):
...
# like this, the commands defination should be cog defination indent level+1
#commands.command()
...
# NOT like this
#commands.command()
...

Making a Slash Command appear in Discord UI

On discord, the module discord.ext.commands lets you create commands. I tried to create a command, with prefix="/", although it won't appear in discord's UI.
Code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="/")
#bot.command(name="kick", description="Kick a user to your wish.")
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"The user #{member} has been kicked. Reason: {reason}.")
bot.run("mytoken")
It won't pop up.
But I want to do it like this:
You need to install discord-py-slash-command and then put the code to import it from discord-py-slash-command import SlashCommands. You can refer the code below:
import discord
from discord_slash import SlashCommand
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True) # Declares slash commands through the client.
guild_ids = [1234567890] # Put your server IDs in this array.
#slash.slash(name="ping", guild_ids=guild_ids)
async def _ping(ctx):
await ctx.send("Pong!")
client.run("token")

Cogs not working in discord.py load extension

import discord
from discord.ext import commands
class CommandEvents(commands.cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("**Invalid command. Try using** `help` **to figure out commands!**")
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please pass in all requirements.**')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements or permissions for using this command :angry:**")
#commands.command(name="ping")
async def ping(self, ctx: commands.Context):
await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms")
def setup(bot):
bot.add_cog(CommandEvents(bot))
thats my cog. When im trying to setup the Bot this will happen. so idk i searched so much how i can use cogs but idk. Im new to cogs this is my first time using them.
my Main Pogramm
import discord
import os
from discord.ext import commands
token = ""
bot = commands.Bot(command_prefix = '-')
bot.load_extension("CommandEvents")
bot.run(token)
what am i doing wrong?
Line 4 of your cog file: You typed commands.cog. Since Python is case sensitive, you have to type commands.Cog with the C in uppercase.
Also:
You have to put in the full path of the cog. You've just typed "CommandEvents" but it should be "cogs.CommandEvents".

Discord.py bot doesn't recognize commands from cogs

I've been trying to figure out how cogs work with the discord.py rewrite and I managed to get a bot working with only one cog. The problem is, the bot recognizes commands from one cog, but not the other.
importing the cogs in bot.py
cogs = [
'cogs.basic',
'cogs.mod']
#bot.event
async def on_ready():
print("Arthur Morgan")
print("version: "+version)
game = discord.Game("rebuilding.....")
await bot.change_presence(status=discord.Status.idle, activity=game)
for extension in cogs:
bot.load_extension(extension)
return
inside basic.py commands inside here seem to work
import discord
from discord.ext import commands
class Basic(commands.Cog):
def __init__(self,bot):
self.bot = bot
#commands.command(name='ping', aliases=['p'])
async def ping(self, ctx):
await ctx.send("Pong! :ping_pong:")
def setup(bot):
bot.add_cog(Basic(bot))
commands in mod.py output this
import discord
from discord.ext import commands
class Mod(commands.Cog):
def __init__(self,bot):
self.bot = bot
#commands.command()
async def pong(self, ctx):
await ctx.send("Ping!")
def setup(bot):
bot.add_cog(Mod(bot))
does anybody know how to fix this?
for extension in cogs:
bot.load_extension(extension)
return
The coroutine stops when it reaches return, after loading only one cog.

role specific command

role specific command yes its working finally got it.
from discord.ext import commands
bot = commands.Bot('?')
#bot.command(pass_context=True)
#commands.has_any_role("Admin", "Moderator")
async def hello(ctx):
await bot.say("Hello {}".format(ctx.message.author.mention))
You can use the discord.ext.commands extension, which offers a has_any_role decorator.
from discord.ext import commands
bot = commands.Bot('?')
#bot.command(pass_context=True)
#commands.has_any_role("Admin", "Moderator")
async def hello(ctx):
await bot.say("Hello {}".format(ctx.message.author.mention))

Categories

Resources