TypeError: 'module' object is not callable

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
MauroMauHD
User
Beiträge: 9
Registriert: Freitag 3. September 2021, 15:49

Bitte hilft mir ich bin einen discord bot am coden und komme nicht weiter.

Code: Alles auswählen

 import discord
from discord import client
from discord import embeds
from discord import colour
from discord import file
from discord.colour import Color
from discord.ext import commands
from discord.ext.commands.core import has_permissions
from discord.guild import BanEntry
import pytz
from datetime import datetime

intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
bot.warnings = {} # guild_id : {member_id: [count, [(admin_id, reason)]]}
bot.remove_command("help")

@bot.event
async def on_ready():
    for guild in bot.guilds:
        bot.warnings[guild.id] = {}
        
        async with aiofiles(f"{guild.id}.txt", mode="a") as temp:
            pass

        async with aiofiles(f"{guild.id}.txt", mode="r") as file:
            lines = await file.readlines()

            for line in lines:
                data = line.split(" ")
                member_id = int(data[0])
                admin_id = int(data[1])
                reason = " ".join(data[2:]).strip("\n")

                try:
                    bot.warnings[guild.id][member_id][0] += 1
                    bot.warnings[guild.id][member_id][1].append((admin_id, reason))

                except KeyError:
                    bot.warnings[guild.id][member_id] = [1, [(admin_id, reason)]] 
    
    print(bot.user.name + " is ready.")
    
@bot.command(name="help")
async def help(ctx):
    embed = discord.Embed(title=f"Help Menü", description=" ", color=0x4cd137)

    embed.add_field(name="prafix", value=f"```?```")
    embed.add_field(name="userinfo", value=f"```Zeige dir alle infos zu einem User```", inline=False)
    embed.add_field(name="message", value=f"```Lasse den bot dir nachmachen```", inline=False)
    embed.add_field(name="kill", value=f"```kille einen User muhahaha```", inline=False)
    embed.add_field(name="test", value=f"```Teste ob die bot commands online sind```", inline=False)
    embed.add_field(name="help", value=f"```lasse dir dieses menü anzeigen```", inline=False)
    embed.set_footer(text=f'Angefordert von {ctx.author.name} • {ctx.author.id}', icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

@bot.command(name='userinfo')
async def userinfo(ctx, member: discord.Member):
    de = pytz.timezone('Europe/Berlin')
    embed = discord.Embed(title=f'> Userinfo für {member.display_name}',
                          description='', color=0x4cd137, timestamp=datetime.now().astimezone(tz=de))

    embed.add_field(name='Name', value=f'```{member.name}#{member.discriminator}```', inline=True)
    embed.add_field(name='Bot', value=f'```{("Ja" if member.bot else "Nein")}```', inline=True)
    embed.add_field(name='Nickname', value=f'```{(member.nick if member.nick else "Nicht gesetzt")}```', inline=True)
    embed.add_field(name='Server beigetreten', value=f'```{member.joined_at}```', inline=True)
    embed.add_field(name='Discord beigetreten', value=f'```{member.created_at}```', inline=True)
    embed.add_field(name='Rollen', value=f'```{len(member.roles)}```', inline=True)
    embed.add_field(name='Höchste Rolle', value=f'```{member.top_role.name}```', inline=True)
    embed.add_field(name='Farbe', value=f'```{member.color}```', inline=True)
    embed.add_field(name='Booster', value=f'```{("Ja" if member.premium_since else "Nein")}```', inline=True)
    embed.set_footer(text=f'Angefordert von {ctx.author.name} • {ctx.author.id}', icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

@bot.command(name='message')
async def message(ctx, *args):
    await ctx.send(f'{" ".join(args)}')

@bot.command(name="kill")
async def kill(ctx, member: discord.Member):
    await ctx.send(f'{member.display_name} wurde gekillt.')

@kill.error
async def kill_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send('Ich kann ihn nicht finden sry.')

@bot.command(name="test")
async def test(ctx):
    await ctx.send("Test erfolgt der bot funktionirt")

@bot.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, member: discord.Member=None, *, reason=None):
    if member is None:
        return await ctx.send("The provided member could not be found or you forgot to provide one.")
        
    if reason is None:
        return await ctx.send("Please provide a reason for warning this user.")

    try:
        first_warning = False
        bot.warnings[ctx.guild.id][member.id][0] += 1
        bot.warnings[ctx.guild.id][member.id][1].append((ctx.author.id, reason))

    except KeyError:
        first_warning = True
        bot.warnings[ctx.guild.id][member.id] = [1, [(ctx.author.id, reason)]]

    count = bot.warnings[ctx.guild.id][member.id][0]

    async with aiofiles(f"{ctx.guild.id}.txt", mode="a") as file:
        await file.write(f"{member.id} {ctx.author.id} {reason}\n")

    await ctx.send(f"{member.mention} has {count} {'warning' if first_warning else 'warnings'}.")

@bot.command()
@commands.has_permissions(administrator=True)
async def warnings(ctx, member: discord.Member=None):
    if member is None:
        return await ctx.send("The provided member could not be found or you forgot to provide one.")
    
    embed = discord.Embed(title=f"Displaying Warnings for {member.name}", description="", colour=discord.Colour.red())
    try:
        i = 1
        for admin_id, reason in bot.warnings[ctx.guild.id][member.id][1]:
            admin = ctx.guild.get_member(admin_id)
            embed.description += f"**Warning {i}** given by: {admin.mention} for: *'{reason}'*.\n"
            i += 1

        await ctx.send(embed=embed)

    except KeyError: # no warnings
        await ctx.send("This user has no warnings.") 
und das der error

Code: Alles auswählen

 Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\mauro\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "e:\Users\mauro\Desktop\BohnenHD bot\main.py", line 25, in on_ready
    async with asyncio(f"{guild.id}.txt", mode="a") as temp:
TypeError: 'module' object is not callable 
alles geht vom testen aber hänge beim warn :cry:
Benutzeravatar
sparrow
User
Beiträge: 4535
Registriert: Freitag 17. April 2009, 10:28

Die Fehlermeldung passt nicht zum Quelltext.
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

@MauroMauHD,

Da fehlt das open():

Code: Alles auswählen

async with aiofiles.open(f"{guild.id}.txt", mode="a") as temp:
MauroMauHD
User
Beiträge: 9
Registriert: Freitag 3. September 2021, 15:49

sparrow hat geschrieben: Freitag 3. September 2021, 16:20 Die Fehlermeldung passt nicht zum Quelltext.
danke sehe gerade habe das falsche hochgeladen hier ist der code sorry

Code: Alles auswählen

 import asyncio
import discord
from discord import client
from discord import embeds
from discord import colour
from discord import file
from discord.colour import Color
from discord.ext import commands
from discord.ext.commands.core import has_permissions
from discord.guild import BanEntry
import pytz
from datetime import datetime

intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
bot.warnings = {} # guild_id : {member_id: [count, [(admin_id, reason)]]}
bot.remove_command("help")

@bot.event
async def on_ready():
    for guild in bot.guilds:
        bot.warnings[guild.id] = {}
        
        async with asyncio(f"{guild.id}.txt", mode="a") as temp:
            pass

        async with asyncio(f"{guild.id}.txt", mode="r") as file:
            lines = await file.readlines()

            for line in lines:
                data = line.split(" ")
                member_id = int(data[0])
                admin_id = int(data[1])
                reason = " ".join(data[2:]).strip("\n")

                try:
                    bot.warnings[guild.id][member_id][0] += 1
                    bot.warnings[guild.id][member_id][1].append((admin_id, reason))

                except KeyError:
                    bot.warnings[guild.id][member_id] = [1, [(admin_id, reason)]] 
    
    print(bot.user.name + " is ready.")
    
@bot.command(name="help")
async def help(ctx):
    embed = discord.Embed(title=f"Help Menü", description=" ", color=0x4cd137)

    embed.add_field(name="prafix", value=f"```?```")
    embed.add_field(name="userinfo", value=f"```Zeige dir alle infos zu einem User```", inline=False)
    embed.add_field(name="message", value=f"```Lasse den bot dir nachmachen```", inline=False)
    embed.add_field(name="kill", value=f"```kille einen User muhahaha```", inline=False)
    embed.add_field(name="test", value=f"```Teste ob die bot commands online sind```", inline=False)
    embed.add_field(name="help", value=f"```lasse dir dieses menü anzeigen```", inline=False)
    embed.set_footer(text=f'Angefordert von {ctx.author.name} • {ctx.author.id}', icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

@bot.command(name='userinfo')
async def userinfo(ctx, member: discord.Member):
    de = pytz.timezone('Europe/Berlin')
    embed = discord.Embed(title=f'> Userinfo für {member.display_name}',
                          description='', color=0x4cd137, timestamp=datetime.now().astimezone(tz=de))

    embed.add_field(name='Name', value=f'```{member.name}#{member.discriminator}```', inline=True)
    embed.add_field(name='Bot', value=f'```{("Ja" if member.bot else "Nein")}```', inline=True)
    embed.add_field(name='Nickname', value=f'```{(member.nick if member.nick else "Nicht gesetzt")}```', inline=True)
    embed.add_field(name='Server beigetreten', value=f'```{member.joined_at}```', inline=True)
    embed.add_field(name='Discord beigetreten', value=f'```{member.created_at}```', inline=True)
    embed.add_field(name='Rollen', value=f'```{len(member.roles)}```', inline=True)
    embed.add_field(name='Höchste Rolle', value=f'```{member.top_role.name}```', inline=True)
    embed.add_field(name='Farbe', value=f'```{member.color}```', inline=True)
    embed.add_field(name='Booster', value=f'```{("Ja" if member.premium_since else "Nein")}```', inline=True)
    embed.set_footer(text=f'Angefordert von {ctx.author.name} • {ctx.author.id}', icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

@bot.command(name='message')
async def message(ctx, *args):
    await ctx.send(f'{" ".join(args)}')

@bot.command(name="kill")
async def kill(ctx, member: discord.Member):
    await ctx.send(f'{member.display_name} wurde gekillt.')

@kill.error
async def kill_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send('Ich kann ihn nicht finden sry.')

@bot.command(name="test")
async def test(ctx):
    await ctx.send("Test erfolgt der bot funktionirt")

@bot.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, member: discord.Member=None, *, reason=None):
    if member is None:
        return await ctx.send("The provided member could not be found or you forgot to provide one.")
        
    if reason is None:
        return await ctx.send("Please provide a reason for warning this user.")

    try:
        first_warning = False
        bot.warnings[ctx.guild.id][member.id][0] += 1
        bot.warnings[ctx.guild.id][member.id][1].append((ctx.author.id, reason))

    except KeyError:
        first_warning = True
        bot.warnings[ctx.guild.id][member.id] = [1, [(ctx.author.id, reason)]]

    count = bot.warnings[ctx.guild.id][member.id][0]

    async with asyncio(f"{ctx.guild.id}.txt", mode="a") as file:
        await file.write(f"{member.id} {ctx.author.id} {reason}\n")

    await ctx.send(f"{member.mention} has {count} {'warning' if first_warning else 'warnings'}.")

@bot.command()
@commands.has_permissions(administrator=True)
async def warnings(ctx, member: discord.Member=None):
    if member is None:
        return await ctx.send("The provided member could not be found or you forgot to provide one.")
    
    embed = discord.Embed(title=f"Displaying Warnings for {member.name}", description="", colour=discord.Colour.red())
    try:
        i = 1
        for admin_id, reason in bot.warnings[ctx.guild.id][member.id][1]:
            admin = ctx.guild.get_member(admin_id)
            embed.description += f"**Warning {i}** given by: {admin.mention} for: *'{reason}'*.\n"
            i += 1

        await ctx.send(embed=embed)

    except KeyError: # no warnings
        await ctx.send("This user has no warnings.") 
tut mir leid habe mich verklickt der fehlercode ist aber richtig
Benutzeravatar
pillmuncher
User
Beiträge: 1530
Registriert: Samstag 21. März 2009, 22:59
Wohnort: Pfaffenwinkel

@MauroMauHD: Der Fehler ist immer noch derselbe auf den dich schon rogerb hingewiesen hatte.
In specifications, Murphy's Law supersedes Ohm's.
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

@MauroMauHD,

in deinem ursprünglichen code war das:

Code: Alles auswählen

async with aiofiles(f"{guild.id}.txt", mode="a") as temp:
Das führte zu deiner Fehlermeldung

Code: Alles auswählen

async with asyncio(f"{guild.id}.txt", mode="a") as temp:
TypeError: 'module' object is not callable 
denn, ja, aiofiles ist ein modul und kann nicht als Funktion aufgerufen werden:

Darauf hatte ich dir gesagt, dass man die open() Funktion von aiofiles verwenden muss und nicht das Modul selbst.

Code: Alles auswählen

async with aiofiles.open(f"{guild.id}.txt", mode="a") as temp:
"aiofiles" wirst du wohl auch importieren müssen.

Jetzt hast du aber aus aiofiles einfach asyncio gemacht, was auch ein Modul ist und was auch nicht als Funktion aufgerufen werden kann.

Code: Alles auswählen

async with asyncio(f"{guild.id}.txt", mode="a") as temp:
Das ist zwar geändert, führt aber zur gleichen Fehlermeldung, da asyncio nunmal keine Funktion ist.

Ein gut gemeinter Rat: Kopiere nicht einfach Code aus dem Internet ohne zu verstehen was er tut.
Antworten