Error "list index out of range" in Python 3 - python

I am currently programming a Discord Bot for a friend.
I have a new PC and now the following error occured after using my "!meme" command.
It worked on my old Laptop, but i dont have it anymore...
Code for the command:
elif '!meme' in message.content:
random_message_i = ["Here you go:", "Classic one:", "This one is good:", "lol xD:"]
await message.channel.send(f"{random.choice(random_message_i)}")
meme_file_paths = [os.path.abspath(_) for _ in glob.glob("botmemes/*.png")]
random_meme_i = random.choice(meme_file_paths)
await message.channel.send(file=discord.File(random_meme_i))
print("[INFO] Last command: !meme")
Error:
Traceback (most recent call last):
File "C:\Users\cxyro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\cxyro\Desktop\DiscordBot\discordbot.py", line 103, in on_message
random_meme_i = random.choice(meme_file_paths)
File "C:\Users\cxyro\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range
(Yes, the code ant the memes are in the same main folder...)
Can somebody help me?

As far as, I can see , it occurs when you pass an empty list to choice() function. (in case, file not found) P.S :- Make sure, you are executing that script within the same directory where your code and meme is kept. otherwise, your current working directory gets changed and your code won't be able to find the meme path. you can verify this by writing this code in a print statement in your script:
import os; os.getcwd()

Related

AttributeError: module 'nats' has no attribute 'connect'

https://nats-io.github.io/nats.py/modules.html
Traceback (most recent call last):
File "c:\Users\lb\nats.py", line 22, in <module>
asyncio.run(main())
File "D:\anaconda\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "D:\anaconda\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "c:\Users\lb\nats.py", line 6, in main
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
AttributeError: module 'nats' has no attribute 'connect'
An Attribute error: I am not able to figure out what is the issue with 'connect'.
import asyncio
import nats
async def main():
# Connect to NATS!
nc = await nats.connect(servers=["nats://216.48.189.5:4222"])
# Receive messages on 'foo'
sub = await nc.subscribe("foo")
# Publish a message to 'foo'
await nc.publish("foo", b'Hello from Python!')
# Process a message
msg = await sub.next_msg()
print("Received:", msg)
# Close NATS connection
await nc.close()
if __name__ == '__main__':
asyncio.run(main())
Help me with this connect issue, please.
The solution is to rename your file to anything else.
When you type import nats python recursively tries to find a file or folder named nats. In this case the first file if will find is nats.py.
You never define a function named connect in your nats.py so that fails. You want to instead let the recursive import continue upto site_packages where the actual nats folder is that contains the connect function.
For example, if you name this file hello.py:
import hello
print(hello.hello)
print(hello)
print(hello.hello.hello)
You will see that all 3 print statements print the same thing, since hello will be the file itself.
Simply renaming your file anything else will prevent python from finding the module too soon and will keep searching till it find the correct module.
I just ran your code and got no error.
Try uninstalling and reinstalling nats:
pip install nats-py

Exception has occurred: NoEntryPointError

I am using Discord.py, and while making a command handler using COG, I got this error.
This is the main.py (main bot file)
# Command Handler: Import cog files.
for file in os.listdir("./cogs"): # lists all the cog files inside the cog folder.
if file.endswith(".py"): # It gets all the cogs that ends with a ".py".
name = file[:-3] # It gets the name of the file removing the ".py"
client.load_extension(f"cogs.{name}") # This loads the cog.
Here is the link to the only file I have in my ./cog/ directory, named "Hellgoodbye.py".
https://pastebin.com/TdE8FPxq
The error I get when I do "python .\main.py" in my VSCode terminal, I get the following error:
Traceback (most recent call last):
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 612, in _load_from_module_spec
setup = getattr(lib, 'setup')
AttributeError: module 'cogs.Hellogoodbye' has no attribute 'setup'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".\main.py", line 141, in <module>
client.load_extension(f"cogs.{name}") # This loads the cog.
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\quinn\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 615, in _load_from_module_spec
raise errors.NoEntryPointError(key)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.Hellogoodbye' has no 'setup' function
Can someone help me fix the error. i really do not know what is going on.
As the error says you don't have setup function. It is necesary for an extension to load.
import discord
from discord.ext import commands
class Name(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Name(bot))
This is an example of a cog file. As you can see at the very end of the code there is the setup function. It should be a standalone function which is not defined inside of the class.
Answer:
I moved
def setup(bot)
bot.add_cog(Hellogoodbye(bot))
To the end of the file, and it is working now, besides the fact I have some other issues, but the error I asked about is fixed by this.

Translation in discord.py bot doesn't work

I've been trying to make my discord bot translate texts using a module called googletrans. It seems fairly simple and it should have worked without any hassle, or so I thought.
So after my import statements, I have translator = Translator().
My following cog code is:
#commands.command(aliases=["tl", "Tl", "Translate"])
async def translate(self, ctx, *, message):
language = translator.detect(message)
translation = translator.translate(message)
embed = discord.Embed(color=discord.Color.dark_theme())
embed.add_field(name=f"Language: {language} ", value=f'{translation}')
await ctx.send(embed=embed)
But it shows this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'group'.
Where am I going wrong? Any help would be much appreciated!
Edit: the full traceback:
Ignoring exception in command translate:
Traceback (most recent call last):
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\wave computer\PycharmProjects\pythonProject\cogs\translate.py", line 13, in translate
language = translator.detect(message)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\googletrans\client.py", line 255, in detect
data = self._translate(text, 'en', 'auto', kwargs)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\googletrans\client.py", line 78, in _translate
token = self.token_acquirer.do(text)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\googletrans\gtoken.py", line 194, in do
self._update()
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\googletrans\gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\wave computer\PycharmProjects\pythonProject\venv\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: AttributeError: 'NoneType' object has no attribute 'group'
I had a same problem. Installing alpha version of google trans helped, so try doing this:
pip install googletrans==3.1.0a0
And:
from googletrans import Translator
#client.command()
async def translate(ctx, lang, *, thing):
translator = Translator()
translation = translator.translate(thing, dest=lang)
await ctx.send(translation.text)
I cannot add comments since I do not have enough reputation, so I will edit this post once I get more information about your code.
Could you please upload the full traceback? Also what happens if before calling the method group on the object, you ensures that it is not None ? (I don't know if this is in your code or in the library)
Have you tried debugging and checking at each step what the variables are and if they are not what you think they should be
Finally, I also think that maybe your variable message is always empty, since you catch other parameters with * right before message so this makes the message parameter a keyword-only parameter, which, to the best of my knowledge cannot be passed when using a bot command
Have you tried changing your function's signature to this :
async def translate(self, ctx, message):
?
UPDATE : From what it seems, the problem happens inside the library, however this can happen if the parameter given to the library function is ill-formed.
If you simulate the bot command (await the method in a main file with ctx=None and message="Hello my friend, how are you today ? I hope you are fine"), what happens?
As can be seen on the pypi page about googletrans on section "Language detection", most of the time the function is called with a sentence. Maybe if the sentence is short enough, the detection does not work ?
Also, I think you should indicate in your question what library you are using because there is also Google's official translate API that can be used

Python exclude CWD file in proc

I have a script called client that does a few things around the OS and it's failing when it comes to /proc/1/cwd
I'm trying to ignore these types of files but the script is still crashing when it comes to this file. I get Memory Map output and also a Stack Trace before the script crashes.
I did a file /proc/1/cwd command on the file and I can see it's a symlink, where I then included an if os.path.islink(file) is False: IF statement to skip it and proceed.
However, I seem to still be hitting it.
The below is the Traceback after the crash.
Traceback (most recent call last):
File "client.py", line 235, in <module>
File "client.py", line 120, in runner
OSError: [Errno 13] Permission denied: '/proc/1/cwd'
Failed to execute script client
The error suggests the script client is working on /proc/1/cwd and then right after seems to say that it can't execute itself?
Any help would be appreciated.
-----Additional -------
Code lines from error:
like 235 is literally the line runner(path)
runner() represents a function that has a for loop that cycles through files in a folder to find the correct file. During this process, runner will do the following:
do line 120 mode = os.stat(fullfilename).st_mode
check if os.path.isdir(fullfilename) is False:
then if stat.S_ISREG(mode) is True:
then if os.path.islink(fullfilename) is False:
then if fullfilename not in blacklist:
Line 120 is mode = os.stat(fullfilename).st_mode

Python + Tweepy, Status is a duplicate

Currently my Python + Tweep bot isn't working claiming the status is a duplicate. The exact error is
Traceback (most recent call last):
File "helloworld.py", line 22, in <module>
api.update_status(line)
File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 230, in _call
return method.execute()
File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 203, in execute
raise TweepError(error_msg, resp)
tweepy.error.TweepError: [{u'message': u'Status is a duplicate.', u'code': 187}]
The bot source is here: https://ghostbin.com/paste/vbdn4 .
What can I add to work around this error?
Note that the first time running this there were no errors yet after stopping it and then going to run it again, I got this error.
you forget to step to the next line of the .txt file you're feeding in the for-loop (it does have multiple lines, doesn't it?), I guess....
I've got the same problem ;-) Tried to solve it with 3 different .txt files and give 3 args in a whlie loop, but this doesn't fly either.
We'll get there....

Categories

Resources