I have this module I made for a discord.py bot (not a COG though). It clearly has the function "help_command" defined but whenever I try to run it it gives me the above error. I couldn't wrap my head around it so I thought it might worth it to ask the community.
discord_main.py
import discord
from discord.ext import commands
import gsheet
import os
import embed_storage
async def help(ctx, argument='Helping'):
await ctx.send(embed=embed_storage.help_command('stargazer', argument))
embed_storage.py
import discord
from cogs.points import points_help_dict
from discord_main import help_dictionary
import gsheet
def help_command(cog_name: str, command: str):
if cog_name == 'stargazer':
use_dict = help_dictionary
title = 'Help'
description = 'Learn how the Stargazer Bot works'
footer_message = 'Prefix for this bot is \'a\''
else:
raise UnboundLocalError(
"Yeh this part of the code should have never run.")
command = command.lower()
if command in use_dict:
title = command.title()
description = use_dict[command]
field = False
help_command_embed = discord.Embed(
title=title,
description=description,
colour=discord.Colour.from_rgb(234, 255, 208)
)
return help_command_embed
Any help would be amazing. Also sorry for the dumb question. Just couldn't wrap my head around this silly error.
Edit: Tried Rolling back to my latest working version of the code and when I ran that. It still gave me the same error. So the error is not in the newly added code
I think the problem is that you are importing from discord_main in embed_storage and vice-versa.
You need to resolve this somehow or, if there is no other way, you could move the import into the function definition, e.g. in embed_storage.py:
def help_command(cog_name: str, command: str):
from discord_main import help_dictionary
if cog_name == 'stargazer':
use_dict = help_dictionary
# ...
Good day,
I am trying to implement the mitmproxy into a bigger application.
For that, I need to be able to load those so called inline scripts in my code and not via command line. I could not find any helpful information about that in the documentation.
I am using mitmproxy version 0.17 and Python 2.7.
I know there is a newer version available, but that one didnt worked using the code examples.
This is the base code I have:
from mitmproxy import controller, proxy
from mitmproxy.proxy.server import ProxyServer
class ProxyMaster(controller.Master):
def __init__(self, server):
controller.Master.__init__(self, server)
def run(self):
try:
return controller.Master.run(self)
except KeyboardInterrupt:
self.shutdown()
def handle_request(self, flow):
flow.reply()
def handle_response(self, flow):
flow.reply()
config = proxy.ProxyConfig(port=8080)
server = ProxyServer(config)
m = ProxyMaster(server)
m.run()
How could I run this proxy using inline scripts?
Thanks in advance
I figured myself out a really ugly workaround.
Instead of using controller.Master I had to use flow.FlowMaster as the controller.Master lib does not seem to be able to handle inline scripts.
For some reason just loading the files did not work, they get triggered immediately, but not by running their matching hooks.
Instead of using the hooks which are not working, I am loading the matching functions as you can see in handle_response (try/except is missing and threading could be useful)
from mitmproxy import flow, proxy
from mitmproxy.proxy.server import ProxyServer
import imp
class ProxyMaster(flow.FlowMaster):
def run(self):
try:
return flow.FlowMaster.run(self)
except KeyboardInterrupt:
self.shutdown()
def handle_request(self, flow):
flow.reply()
def handle_response(self, flow):
for inline_script in self.scripts:
script_file = imp.load_source("response", inline_script.filename)
script_file.response(self, flow)
flow.reply()
proxy_config = proxy.ProxyConfig(port=8080)
server = ProxyServer(proxy_config)
state = flow.State()
m = ProxyMaster(server, state)
m.load_script("upsidedowninternet.py")
m.load_script("add_header.py")
m.run()
Any ideas about doing it the right way are appreciated.
I am trying to use the sendMessage function provided by WebSocketServerProtocol in a seperate file/class but getting exceptions.
class MyServerProtocol(WebSocketServerProtocol):
def onMessage(self, payload, isBinary):
#input = payload
#print payload
# echo back message verbatim
#self.sendMessage(payload, isBinary)
cg = coreg.DataGatherCg
cg.test(cg())
in coreg:
from appserver import MyServerProtocol
from autobahn.twisted.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
class DataGatherCg(MyServerProtocol):
def test(self):
MyServerProtocol.send(self,'test',False)
I am getting the error:
(<type 'exceptions.AttributeError'>): 'DataGatherCg' object has no attribute 'state')
I am trying to put it in a seperate file and class as the class will eventually be huge and I would prefer to have them separate so I can keep track of everything.
Any suggestions on how to do this?
UPDATE: Can someone provide an example of how to "...split a class due to complexity, create a mix-in class and inherit from it."
(i know this resembles Python and d-bus: How to set up main loop? , but without complete code in the "Answer", i'm unable to figure out where i'm going wrong. it might just be a change in a Skype)
Here is my program:
import gobject
import dbus
import dbus.mainloop.glib
dbus_gmainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
sessbus = dbus.SessionBus()
skype = sessbus.get_object('com.Skype.API', '/com/Skype')
skypec = sessbus.get_object('com.Skype.API', '/com/Skype/Client')
skype_iface = dbus.Interface(skype, dbus_interface='com.Skype.API')
skype_iface.Invoke("NAME py1")
# ... waits for user click in Skype ...
#==> dbus.String(u'OK')
skype_iface.Invoke("PROTOCOL 7")
#==> dbus.String(u'PROTOCOL 7')
def got_signal(sender, destination, member, interface, path):
print "got_signal(sender=%s, dest=%s, member=%s, iface=%s, path=%s)" \
% (sender, destination, member, interface, path)
skypec.connect_to_signal('Notify', got_signal, sender_keyword='sender', \
destination_keyword='destination', member_keyword='member', \
interface_keyword='interface', path_keyword='path')
mainloop = gobject.MainLoop()
mainloop.run()
When run (e.g. python skype-call.py), it pauses after sending the NAME py1 command to Skype and waits for an interactive confirmation in the Skype UI, then continues. As such, the skype_iface object is clearly working at least to a certain degree.
However, python then emits the following error:
ERROR:dbus.proxies:Introspect error on :1.152:/com/Skype/Client: dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownObject: No such object path '/com/Skype/Client'
I also tried the following (instead of connect_to_signal, just before starting the gobject mainloop at the end):
def receiver(x, **kwargs):
print "receiver(%s)" % (x,)
sessbus.add_signal_receiver(receiver, signal_name='Notify', \
dbus_interface='com.Skype.API', bus_name='com.Skype.API', path='/com/Skype/Client')
And while that didn't complain, it never gets called. I tried sending the Skype user a message. What sorts of events should trigger it?
The docs at https://dev.skype.com/desktop-api-reference#DBUSUsage aren't terribly helpful.
This is Skype for Linux 4.2.0.11 on Debian 7.0 multiarch (amd64/i386).
looking back at http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-methods-with-dbus-service-method , i tried taking their example:
import gobject
import dbus
from dbus.decorators import method
import dbus.mainloop.glib
import dbus.service
dbus_gmainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
sessbus = dbus.SessionBus()
class Example(dbus.service.Object):
def __init__(self, bus):
dbus.service.Object.__init__(self, bus, '/com/Skype/Client')
#method(dbus_interface='com.Skype.API.Client', in_signature='s', \
sender_keyword='sender', destination_keyword='dest', \
rel_path_keyword='rel_path', path_keyword='path', \
message_keyword='message', connection_keyword='conn')
def Notify(self, s, sender=None, dest=None, rel_path=None, path=None, \
message=None, conn=None):
print "Notify(%s, sender=%s, dest=%s, rel_path=%s, path=%s, message=%s, conn=%s)" \
% (s, sender, path, dest, message, rel_path, conn,)
# make one:
ex = Example(sessbus)
skype = sessbus.get_object('com.Skype.API', '/com/Skype')
skype_iface = dbus.Interface(skype, dbus_interface='com.Skype.API')
skype_iface.Invoke("NAME py1")
##=> dbus.String(u'OK')
skype_iface.Invoke("PROTOCOL 7")
##=> dbus.String(u'PROTOCOL 7')
mainloop = gobject.MainLoop()
mainloop.run()
and lo and behold i get Notify calls:
Notify(CONNSTATUS ONLINE, sender=:1.152, path=/com/Skype/Client, dest=:1.275, message=<dbus.lowlevel.MethodCallMessage path: /com/Skype/Client, iface: com.Skype.API.Client, member: Notify dest: :1.275>, rel_path=/, conn=<dbus._dbus.SessionBus (session) at 0x2118e90>)
Notify(CURRENTUSERHANDLE ******, sender=:1.152, path=/com/Skype/Client, dest=:1.275, message=<dbus.lowlevel.MethodCallMessage path: /com/Skype/Client, iface: com.Skype.API.Client, member: Notify dest: :1.275>, rel_path=/, conn=<dbus._dbus.SessionBus (session) at 0x2118e90>)
Notify(USERSTATUS ONLINE, sender=:1.152, path=/com/Skype/Client, dest=:1.275, message=<dbus.lowlevel.MethodCallMessage path: /com/Skype/Client, iface: com.Skype.API.Client, member: Notify dest: :1.275>, rel_path=/, conn=<dbus._dbus.SessionBus (session) at 0x2118e90>)
Obviously, this isn't a great example of a well-structured program, but the d-bus bits do appear to connect.
I'm trying to debug the same thing, maybe we can sort something out together (I'm using wheezy amd64 too, btw)...
From what I understood, it looks like com.Skype.API is not exposing an object named /com/Skype/Client (and d-feet confirms that).
I used dbus-monitor to monitor the bus while sending a message to my skype account. Amongst the other output, I got this:
method call sender=:1.43 -> dest=:1.132 serial=324 path=/com/Skype/Client; interface=com.Skype.API.Client; member=Notify
string "CHAT #rshk-testuser1/$myusername;<hex-code-here> ACTIVITY_TIMESTAMP 1370647479"
error sender=:1.132 -> dest=:1.43 error_name=org.freedesktop.DBus.Error.UnknownMethod reply_serial=324
string "Method "Notify" with signature "s" on interface "com.Skype.API.Client" doesn't exist
"
method call sender=:1.43 -> dest=:1.132 serial=325 path=/com/Skype/Client; interface=com.Skype.API.Client; member=Notify
string "CHATMESSAGE 1538281 STATUS RECEIVED"
error sender=:1.132 -> dest=:1.43 error_name=org.freedesktop.DBus.Error.UnknownMethod reply_serial=325
string "Method "Notify" with signature "s" on interface "com.Skype.API.Client" doesn't exist
"
So, it looks like there's another interface named com.Skype.API.Client that's exposing the /com/Skype/Client object, but for some reason that interface is unreachable..
I had a look at /etc/dbus-1/system.d/skype.conf that's only listing com.Skype.API.
I'm not very experienced with dbus, but I'm trying to dig further and understand what's wrongs..
In Django I wrote a custom command, called update.
This command is continously called by a shell script and updates some values in the database. The updates are done in threads. I put the class doing all-threading related things in the same module as the custom command.
On my production server, when I try to run that shell script, I get an error when I try to access my models:
antennas = Antenna.objects.all()
The error is:
AttributeError: 'NoneType' object has no attribute 'objects'
As you can see, however, I did import app.models.Antenna in that file.
So to me, it seems as if the reference to the whole site is somehow "lost" inside the threading class.
site/app/management/commands/update.py
(I tried to remove all non-essential code here, as it would clutter everything, but I left the imports intact)
from django.core.management.base import NoArgsCommand, CommandError
from django.utils import timezone
from datetime import datetime, timedelta
from decimal import *
from django.conf import settings
from _geo import *
import random, time, sys, traceback, threading, Queue
from django.db import IntegrityError, connection
from app.models import Bike, Antenna
class Command(NoArgsCommand):
def handle_noargs(self, **options):
queue = Queue.Queue()
threadnum = 2
for bike in Bike.objects.filter(state__idle = False):
queue.put(bike)
for i in range(threadnum):
u = UpdateThread(queue)
u.setDaemon(True)
u.start()
queue.join()
return
class UpdateThread(threading.Thread):
def init(self, queue):
threading.Thread.init(self)
self.queue = queue
def run(self):
antennas = Antenna.objects.all()
while not self.queue.empty():
try:
[...]
except Exception:
traceback.print_exc(file=sys.stdout)
finally:
self.queue.task_done()
When I try to from app.models import Antenna inside the UpdateThread-class I get an error:
ImportError: No module named app.models
The site runs great on a webserver. No model-related problems there, only when I do anything inside a thread - all app.models-imports are failing.
Additionally, it seems to me as exactly the same configuration (I'm using git) does run on another machine, which runs the same operating system (debian wheezy, python 2.7.3rc2 & django 1.4.2).
Very probably I'm missing something obvious about threading here but I'm stuck for far too long now. Your help would be very much appreciated!
PS: I did check for circular imports - and those shouldn't happen anyway, as I can use my models in the other (management-)class, right?