Unable to log a cog, gettin ExtensionNotFound - python-3.x

I'm not sure if I'm missing something here, but I have a .py file in my cogs folder that will not load. Keeps giving me error ```The above exception was the direct cause of the following exception:
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.determineHit' could not be loaded.
The following is a picture of my file locations:
https://imgur.com/a/gBbX4lM
I will copy the code here as well for you to see, but will snip the bulk of the code as it is quite long. If you need further information, please let me know.
import discord
import json
import random
import os
import time
from pathlib import Path
from threading import Timer
from discord.ext import commands
# from Roll_not_strike import *
# from Roll_true_strike import *
# from playerone_zero_current_hp import *
# from playertwo_zero_current_hp import *
def evasionTimer(self):
pass
class Hit(commands.Cog):
def __init__(self, client):
self.client = client
# Bulk of Code
def setup(client):
client.add_cog(Hit(client))
With the main script of the bot being:
import discord
import os
from discord.ext import commands
token = open("token.txt", "r").read()
client = commands.Bot(command_prefix = '!')
#client.command()
async def load(ctx, extension):
client.load_extension("cogs." + extension)
#client.command()
async def unload(ctx, extension):
client.unload_extension("cogs." + extension)
for filename in os.listdir("./cogs"):
if filename.endswith('.py'):
client.load_extension("cogs." + filename[:-3])
client.run(token)
Every other cog in the cogs folder loads up just fine, should I remove determineHit.py I am not sure what I'm missing here. Any help would be appreciated.
Edit:
Before the request for a trace back was asked for, I started thinking on what was going on, and came to the conclusion that the file determineHit.py doesn't really use any discord commands. What is happening is user types in command to discord !roll, bot see that !roll command points to a method in determineHit.py where all the calculations are done (The code in that file is pure python, nothing calling upon discord commands), and then returns that data back to the bot, with all data that needs to be sent to the chat stored in a dictonary called msgwhich then has a for loop to print out all necessary information.
Example, in determineHit.py, you might find:
msg = []
msg.append("Hi Peoples!")
msg.append("Wow! You hit someone!")
msg.append("Aww! You missed!")
msg.append("These are Examples!)
return msg
back in the bot itself, it would unpack msg and print out the statements stored within with a for loop:
for msg_item in msg:
await ctx.send(msg_item)
Long story short, I assumed that because determineHit.py isn't using anything from the discord library, it doesn't need to be a cog, it can be in another folder in the same directory.
So I did this:
https://imgur.com/a/qM7v8E4
Hoping that might solve my problem. (The other files under determineHit.py are the same, they are just python files containing calculations and the like, they call on no methods in any discord library.)
Evidently, I am wrong. As when I try to run the bot with from determineHit import * I get the extension error that started this all. Run it without the above, and bot starts, but obviously can't run the command, because the method it calls on doesn't exist, because it can't see determineHit.py
Probably more wordy than you needed, I'm sorry. But anyway...
I also did the traceback someone reqested, and I got the following:
"C:\Users\arrae\PycharmProjects\Python Learning\venv\Scripts\python.exe" C:/Users/arrae/PycharmProjects/DiscordDiceGame/BotCommands.py
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
'Bot' object has no attribute 'load_extensions'
Bot is Online
mind you that this was done after I moved determineHit.py out of cogs, and put it in 'gamelogic' folder.
However, if it does help, I put determineHit.py back in the cogs folder, and ran the same traceback code offered:
"C:\Users\arrae\PycharmProjects\Python Learning\venv\Scripts\python.exe" C:/Users/arrae/PycharmProjects/DiscordDiceGame/BotCommands.py
Traceback (most recent call last):
File "C:\Users\arrae\PycharmProjects\Python Learning\venv\lib\site-packages\discord\ext\commands\bot.py", line 621, in load_extension
lib = importlib.import_module(name)
File "C:\Users\arrae\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\arrae\PycharmProjects\DiscordDiceGame\cogs\determineHit.py", line 10, in <module>
from Roll_not_strike import *
ModuleNotFoundError: No module named 'Roll_not_strike'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/arrae/PycharmProjects/DiscordDiceGame/BotCommands.py", line 25, in <module>
client.load_extension("cogs." + filename[:-3])
File "C:\Users\arrae\PycharmProjects\Python Learning\venv\lib\site-packages\discord\ext\commands\bot.py", line 623, in load_extension
raise errors.ExtensionNotFound(name, e) from e
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.determineHit' could not be loaded.
I'm sorry if I just made things more complicated. Thought I had found my own answer.

I would like to see an actual traceback.
You can create a dictionary, list each cog and see if it helps.
async def on_ready():
print('Bot is ready')
initial_extensions = (
'cogs.charCreation',
'cogs.charFeats',
'cogs.charSheet',
'cogs.gameCombat',
'cogs.determineHit'
)
for extension in initial_extensions:
try:
client.load_extensions(extension)
except Exception as e:
print(e)
Source: https://github.com/Rapptz/RoboDanny/blob/rewrite/bot.py
Edit: You need to place code above right to the main file after
client = commands.Bot(command_prefix = '!')
Put determineHit.py back to folder with cogs.
Right after
import discord
import os
from discord.ext import commands
paste the following lines to the main file
from gamelogic import onPRIUTil, playerone_zero_current_hp, playertwo_zero_current_hp, Roll_not_strike, Roll_true_strike

Related

Telegram bot polling function

This is my first time trying to make a telegram bot.
Code:
import os
import telebot
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)
#bot.message_handler(commands=['hello'])
def send_welcome(message):
bot.reply_to(message, "HI!")
bot.polling()
Error:
Traceback (most recent call last):
File "/Users/anshtyagi/Documents/telegram bot/main.py", line 23, in <module>
bot.polling()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 621, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 695, in __threaded_polling
raise e
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 650, in __threaded_polling
polling_thread.raise_exceptions()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/util.py", line 111, in raise_exceptions
raise self.exception_info
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/util.py", line 93, in run
task(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 360, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1),
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/__init__.py", line 338, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates, long_polling_timeout)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/apihelper.py", line 324, in get_updates
return _make_request(token, method_url, params=payload)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/telebot/apihelper.py", line 80, in _make_request
raise Exception('Bot token is not defined')
Exception: Bot token is not defined
I am getting this error while running my telegram bot this is my first time. I have seen some tutorials how to make a bot but mine is not working. I have posted my token in .env file and imported it using os.getenv. I am just simply trying to make a simple bot just for my knowledge as I have tried making discord bots and it was great experience and I learned many new languages so I thought why not try this also.
I'm also new to python and telegram bots, but my first bot is running ok and I see the problem in your code. Your exception tells us Exception: Bot token is not defined. So your script doesn't get a token from the system var.
You say that you have your token in .env file. To get os variable from that file first of all we must import a module: from dotenv import load_dotenv.
Next we must import variables from that file using the function load_dotenv().
After that we can read our variables with os.getenv. So that line of your code seems to be correct. If there is no variable in the file os.getenv should get it from the os.
So your code may look like:
import os
import telebot
from dotenv import load_dotenv
load_dotenv()
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)
#bot.message_handler(commands=['hello'])
def send_welcome(message):
bot.reply_to(message, "HI!")
bot.polling()
try this:
import telebot
bot = telebot.TeleBot("API_KEY")
instead of:
import os
import telebot
API_TOKEN = os.getenv('API_KEY')
bot = telebot.TeleBot(API_TOKEN)

How to split my subcommands in several files in Python 3.6 and Click 7.1.2

I would like to implement each subcommand in a different file for a better clarity.
Right now I have only one but the idea will be to add more with the time.
For that I tried 2 ways and it ended with a big failure...
Basically I try to have this result:
$ test_cli
Usage: test_cli [OPTIONS] COMMAND [ARGS]...
Cli command
Options:
--help Show this message and exit.
Commands:
test Test command.
$ test_cli test hello
Hello !
Here are files
$ tree
.
├── cli.py
├── setup.py
└── test.py
I'm using virtualenv and I use the following command to test my application:
$ pip install --editable .
The code of setup.py is the same for both :
from setuptools import setup
setup(
name = 'test_cli',
version = '1.0',
py_modules = [ 'cli', 'test' ],
install_requires = [
'Click',
],
entry_points = '''
[console_scripts]
test_cli=cli:cli
''',
)
Try 1 - FAILURE
Code based on this link, but it did not work with me...
Here is the code of each file:
cli.py
import click
import test
#click.group()
def cli():
''' Cli command '''
pass
cli.add_command(test)
test.py
import click
#click.group()
def test():
''' Test command. '''
pass
#test.command()
def hello():
click.echo('Hello !')
Here is the error I have :
Traceback (most recent call last):
File "/tmp/myenv/bin/test_cli", line 33, in <module>
sys.exit(load_entry_point('test-cli', 'console_scripts', 'test_cli')())
File "/tmp/myenv/bin/test_cli", line 25, in importlib_load_entry_point
return next(matches).load()
File "/tmp/myenv/lib/python3.6/site-packages/importlib_metadata/__init__.py", line 105, in load
module = import_module(match.group('module'))
File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/toto/cli.py", line 9, in <module>
cli.add_command(test)
File "/tmp/myenv/lib/python3.6/site-packages/click/core.py", line 1347, in add_command
name = name or cmd.name
AttributeError: module 'test' has no attribute 'name'
Try 2 - FAILED
This time I found a code here. I don't have any error but I cannot execute any subcommand :-/
cli.py
import click
import test
#click.group()
def cli():
''' Cli command '''
pass
import click
import cli
test.py
import click
import cli
#cli.group()
def test():
''' Test command. '''
pass
#test.command()
def hello():
click.echo('Hello !')
When I execute try to execute the subcommand I have this issue:
$ test_cli test hello
Usage: test_cli [OPTIONS] COMMAND [ARGS]...
Try 'test_cli --help' for help.
Error: No such command 'test'.
Any idea of the issue ?
Thank you.
The easiest way to do this is to implement a separate .py file for your CLI and import the functions into it. I've implemented this in my own program with:
console.py
import click
from .main import store, retrieve
#click.group()
def cli():
pass
#cli.command(no_args_is_help=True)
(series of #click.arguments)
def store(application, key, expiration, userdata):
# sends the arguments directly to the "store" function in main.py
store(application,key,expiration,userdata)
(other commands)
if __name__ == '__main__':
cli()
and in main.py
def store(app, key, expiration, userdata):
"""Program for a user to submit a user-generated API key to their database."""
# The actual function doing its work, in a separate file
This method separates your CLI setup from the actual code, while allowing full access to all of clicks functions including groups, subcommands, etc. It also allows you to call commands from many different modules or even calling external commands within your CLI (for example, if you want a CLI that conglomerates multiple functions from various packages, setting aside the discussion over whether that is appropriate behavior or not).
In your first example you need to import the test group into your module.
cli.py
import click
from test import test
#click.group()
def cli():
''' Cli command '''
pass
cli.add_command(test)
if __name__ == '__main__':
cli()
test.py
import click
#click.group()
def test():
''' Test command. '''
pass
#test.command()
def hello():
click.echo('Hello !')

Exposing Python Script as an API or Service

I am using Python for quite a while. I have integrated my python code with java UI as well and is working fine.
Now here comes the tricky part.
I need to expose my python script as an API so that it can be executed from anywhere (Any other suggestions to achieve this are also welcomed) without depending on one particular machine where the python scripts are present.
My initial basic code snippet is given below for your reference :
import .....
def main(id1, id2):
do something ........
call sub-function(id1, id2)
do something ........
if __name__ == '__main__':
id1 = sys.argv[1] #Getting first argument from Java UI.
id1 = sys.argv[1] #Getting first argument from Java UI.
main(id1, id2) #Calling Main function using two IDs as arguments.
This code is working fine as long as I point to the script path in my system from java. But I need to change this code structure to expose it as an API or Service. I do not have any idea on how to achieve this. With help of few articles, I tried my luck with Flask framework. But I am not sure how to call main function using flask by supplying arguments.
import .....
from flask import Flask
app = Flask(__name__)
#app.route("/")
def main():
do something ........
id1 = app.config.get['ID1']
id2 = app.config.get['ID2']
call sub-function(id1, id2)
do something ........
if __name__ == '__main__':
#For simplicity I supplied the arguments' values manually instead of getting it from java.
app.config['ID1'] = 101
app.config['ID2'] = 2
app.run(debug=True)
#Commented out calling main function since app.run() will take care
#main(id1, id2) #Calling Main function using two IDs as arguments.
When I execute this and goes to default web address (http://127.0.0.1:5000), I am getting the below error
TypeError: 'builtin_function_or_method' object is not subscriptable
Traceback (most recent call last) File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1997, in call return self.wsgi_app(environ, start_response) File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1985, in wsgi_app response = self.handle_exception(e) File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1540, in handle_exception reraise(exc_type, exc_value, tb) File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask_compat.py",
line 33, in reraise raise value File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1982, in wsgi_app response = self.full_dispatch_request() File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1614, in full_dispatch_request rv = self.handle_user_exception(e) File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1517, in handle_user_exception reraise(exc_type, exc_value, tb) File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask_compat.py",
line 33, in reraise raise value File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1612, in full_dispatch_request rv = self.dispatch_request() File
"C:\Users\user_name\Anaconda3\lib\site-packages\flask\app.py", line
1598, in dispatch_request return
self.view_functionsrule.endpoint File
"C:\Users\user_name\Main_Script.py", line 29, in main id1 =
app.config.get['ID1'] TypeError: 'builtin_function_or_method' object
is not subscriptable The debugger caught an exception in your WSGI
application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you
can click on the "Traceback" headline. From the text traceback you can
also create a paste of it. For code execution mouse-over the frame you
want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there
are some extra helpers available for introspection:
dump() shows all variables in the frame dump(obj) dumps all that's
known about the object
Can anyone please let me know how to resolve this and how to execute this script from any machine by exposing it as an API or service.
As I understand you are looking to remotely call the Python function and pass arguments into it and get back the result.
For example:
#app.route('/<string:idOne>/<string:idTwo>')
def main(idOne,idTwo):
do something
return something
Now you can just make a HTTP GET request.
For example:
http://127.0.0.1:5000/myFirstArg/mySecondArg

TypeError: Can't convert 'bytes' object to str implicitly for tweepy

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey=''
csecret=''
atoken=''
asecret=''
class listener(StreamListener):
def on_data(self,data):
print(data)
return True
def on_error(self,status):
print(status)
auth = OAuthHandler(ckey,csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track="cricket")
This code filter the twitter stream based on the filter. But I am getting following traceback after running the code. Can somebody please help
Traceback (most recent call last):
File "lab.py", line 23, in <module>
twitterStream.filter(track="car".strip())
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 430, in filter
self._start(async)
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 346, in _start
self._run()
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 286, in _run
raise exception
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 255, in _run
self._read_loop(resp)
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 298, in _read_loop
line = buf.read_line().strip()
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 171, in read_line
self._buffer += self._stream.read(self._chunk_size)
TypeError: Can't convert 'bytes' object to str implicitly
Im assuming you're using tweepy 3.4.0. The issue you've raised is 'open' on github (https://github.com/tweepy/tweepy/issues/615).
Two work-arounds :
1)
In streaming.py:
I changed line 161 to
self._buffer += self._stream.read(read_len).decode('UTF-8', 'ignore')
and line 171 to
self._buffer += self._stream.read(self._chunk_size).decode('UTF-8', 'ignore')
and then reinstalled via python3 setup.py install on my local copy of tweepy.
2)
remove the tweepy 3.4.0 module, and install 3.3.0 using command: pip install -I tweepy==3.3.0
Hope that helps,
-A
You can't do twitterStream.filter(track="car".strip()). Why are you adding the strip() it's serving no purpose in there.
track must be a str type before you invoke a connection to Twitter's Streaming API and tweepy is preventing that connection because you're trying to add strip()
If for some reason you need it, you can do track_word='car'.strip() then track=track_word, that's even unnecessary because:
>>> print('car'.strip())
car
Also, the error you're getting does not match the code you have listed, the code that's in your question should work fine.

Error when Unzipping with Pyside Qtgui

When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.

Resources