async def run(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: if getFunctionSwitch(token, 'command'): hasPermission = checkPermission(token, 'command', msg.author.roles) if hasPermission is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试联系管理') elif not hasPermission: await reply(msg, '您没有权限执行此指令') else: if len(args) < 2: await reply( msg, '远程执行指令帮助:\n.run <服务器名称> <指令>(若指令内含有引号 请在引号前加 \ 进行反义)\n原版指令无法获取返回 请开启日志转发功能' ) else: command = '' for i in args[1:]: command += f'{i} ' command = command[:-1] success = await runCommand(token, args[0], command) if success == 'offline': await reply(msg, '服务器不在线') elif success == 'failure': await reply(msg, '指令发送失败') else: await addSnType(token, success, 'run') await reply(msg, f'指令发送成功 sn: {success}') else: await reply(msg, '该功能未启用')
async def status(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: if getFunctionSwitch(token, 'status'): hasPermission = checkPermission(token, 'status', msg.author.roles) if hasPermission is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试联系管理') elif not hasPermission: await reply(msg, '您没有权限执行此指令') else: data = await getAllStatus(token) if data is None: await reply(msg, '无服务器在线') else: message = '' for server in data: if data[server]['status'] == 'offline': message += f'{server}: 离线\n' else: message += f'{server}: 在线\n 版本: {data[server]["version"]}\n 在线玩家: ' if len(data[server]['onlinePlayer']) == 0: message += '无\n' else: onlinePlayers = '' for player in data[server]['onlinePlayer']: onlinePlayers += f'{player}, ' onlinePlayers = onlinePlayers[:-2] message += f'{onlinePlayers}\n' await reply(msg, message) else: await reply(msg, '该功能未启用')
async def settellraw(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: adminPm = checkAdmin(token, int(msg.author_id)) if adminPm is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif not adminPm: await reply(msg, '您无权使用该指令') else: if len(args) == 1: success = setTellraw(token, args[0]) if success is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif success: await reply(msg, '设置成功') else: await reply(msg, '未知错误') else: await reply( msg, '参数错误\n设置tellraw帮助:\n - settellraw <json>: 设置开黑啦到服务器消息的tellraw格式, json需转义 (玩家ID: %playerId%, 消息内容: %text%)' )
async def settoken(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is not None: await reply(msg, '已配置token, 若需重设, 请先解绑') else: if len(args) != 1: await reply(msg, '帮助: .settoken <token>') else: message = setToken(args[0], msg.guild_id) await reply(msg, message)
async def unsettoken(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: adminPm = checkAdmin(token, int(msg.author_id)) if adminPm is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif not adminPm: await reply(msg, '您无权使用该指令') else: message = unsetToken(token, msg.guild_id) await reply(msg, message)
async def say(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: if getFunctionSwitch(token, 'say'): hasPermission = checkPermission(token, 'say', msg.author.roles) if hasPermission is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试联系管理') elif not hasPermission: await reply(msg, '您没有权限执行此指令') else: if len(args) < 2: await reply( msg, '参数错误\nsay帮助:\n - say <服务器名称> <消息内容>: 发送消息至服务器, 读取群组内昵称作为ID' ) else: tellraw = getTellraw(token) if tellraw is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试联系管理') else: texts = '' for text in args[1:]: texts += f'{text} ' texts = texts[:-1] tellraw = tellraw.replace( '%playerId%', msg.extra['author']['nickname']).replace( '%text%', texts) command = f'tellraw @a {tellraw}' success = await runCommand(token, args[0], command) if success == 'offline': await reply(msg, '服务器不在线') elif success == 'failure': await reply(msg, '消息发送失败') else: await addSnType(token, success, 'say') channel_id = getChannel(token, 'Chat') if channel_id is None: channel_id = msg.channel_id await bot.send( channel_id=str(channel_id), type=1, content= f'[{args[0]}] [{datetime.datetime.now().strftime("%H:%M")}] {msg.extra["author"]["nickname"]}: {texts}' )
async def function(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: adminPm = checkAdmin(token, int(msg.author_id)) if adminPm is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif not adminPm: await reply(msg, '您无权使用该指令') else: if len(args) != 2: await reply(msg, '设置功能开关帮助: .function <功能名称> true/false') else: message = setFunctionSwitch(token, args[0], args[1]) await reply(msg, message)
async def info(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: config = getServerConfig(token) if config is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: message = '' for functionType, function in config['function'].items(): message += f'{functionType}:\n' for key in function.keys(): message += f' - {key}: {function[key]["enable"]}\n' if 'channel_id' in function[key]: if function[key]['channel_id'] != -1: message += f' channel_id: {function[key]["channel_id"]}\n' message += f'tellraw: {config["tellraw"]}\n' await reply(msg, message)
def magicUpdateScraper(): tosend = False # inizializzo la roba per la valuta url = config.getScrapSite() html = requests.get(url, headers={'Cache-Control': 'no-cache'}).text soup = BeautifulSoup(html, "html.parser") links = soup.findAll('div', {'class': 'calculated-rate'}) valore = str(links)[293:300] converted = "NUOVE STATISTICHE DI STELLAR: \n 1 XLM = " + valore + " €" print(valore) global oldvalue if (oldvalue == 0.0): oldvalue = float(valore) tosend = True if (abs(oldvalue - float(valore)) >= 0.02): tosend = True oldvalue = float(valore) if (tosend): url2 = 'https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s' % ( config.getToken(), config.getId(), converted) _ = requests.get(url2, timeout=10)
async def setchannel(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: adminPm = checkAdmin(token, int(msg.author_id)) if adminPm is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif not adminPm: await reply(msg, '您无权使用该指令') else: if len(args) == 0: await reply( msg, '默认频道: .setchannel default\n恢复所有功能频道至默认: .setchannel reset\n设置单个功能频道: .setchannel <功能名称>' ) elif len(args) == 1: message = setChannel(token, msg.channel_id, args[0]) await reply(msg, message) else: await reply( msg, '参数错误\n默认频道: .setchannel default\n恢复所有功能频道至默认: .setchannel reset\n设置单个功能频道: .setchannel <功能名称>' )
taxt = taxt.split(config.getPower())[1] taxt = taxt.upper() bot.sendMessage("-1001123977184",taxt) if(msg["text"]=="/help@reviubot"): bot.sendMessage(chat_id,"❔ Mi hanno aggiornato raga, finalmente la conversione funziona. Non vi dico più quella di Paypal però, tanto prima mentivo lol") if(msg["text"]=="/reviu@reviubot"): bot.sendMessage(chat_id,"🆘 SONO PRESENTI REVIU' \n\n"+alltags) if(msg["text"]=="/robadauno@reviubot"): bot.sendMessage(chat_id,"1️⃣ SONO PRESENTI ROBE DA 1 BRUTTE \n\n"+alltags) if(msg["text"]=="/robadadue@reviubot"): bot.sendMessage(chat_id,"2️⃣ SONO PRESENTI ROBE DA 2 BRUTTE \n\n"+alltags) if(msg["text"]=="/taskuo@reviubot"): bot.sendMessage(chat_id,"🔞 SONO PRESENTI UPSETTING/OFFENSIVE \n\n"+alltags) if(msg["text"]=="/images@reviubot"): bot.sendMessage(chat_id,"🌄 SONO PRESENTI IMAGE BELLISSIME \n\n"+alltags) if(msg["text"]=="/valuta@reviubot"): bot.sendMessage(chat_id,"💸 Attualmente, 1 dollaro = "+finalmentegiustoconvert+" euro.\n") TOKEN = config.getToken() bot = telepot.Bot(TOKEN) bot.message_loop(on_chat_message) print ('Listening ...') import time while 1: time.sleep(10)
import discord import config as Config import random from discord.ext import commands, tasks import asyncio import rssreader as postman client = discord.Client() TOKEN = Config.getToken() GUILD = int(Config.getGuild()) CH = int(Config.getMusik()) class MyCog(commands.Cog): def __init__(self, bot): self.index = 0 self.bot = bot self.channel = self.bot.get_channel(CH) self.pm = postman.Postman() self.printer.start() def cog_unload(self): self.printer.cancel() @tasks.loop(minutes=10.0) async def printer(self): if len(self.bot.chs) != 0: msg = self.pm.getPosts() await self.bot.do_message(msg) else: await asyncio.sleep(random.uniform(1, 3))
# basic telegram bot # https://www.codementor.io/garethdwyer/building-a-telegram-bot-using-python-part-1-goi5fncay # https://github.com/sixhobbits/python-telegram-tutorial/blob/master/part1/echobot.py import json import requests import time import urllib import config from dialogue import Dialogue # python3: urllib.parse.quote_plus # python2: urllib.pathname2url TOKEN = config.getToken() # don't put this in your repo! (put in config, then import config) URL = "https://api.telegram.org/bot{}/".format(TOKEN) def get_url(url): response = requests.get(url) content = response.content.decode("utf8") return content def get_json_from_url(url): content = get_url(url) js = json.loads(content) return js def get_updates(offset=None): url = URL + "getUpdates"
async def permission(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: adminPm = checkAdmin(token, int(msg.author_id)) if adminPm is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif not adminPm: await reply(msg, '您无权使用该指令') else: if len(args) > 0: if args[0] == 'list': config = getServerConfig(token) if config is None: await reply( msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: message = '' roleData = await bot.get( f'{API_URL}/guild-role/index?compress=0', json={'guild_id': str(msg.guild_id)}) roleIdMapping = {} for i in roleData: roleIdMapping[str(i['role_id'])] = str(i['name']) for function in config['permission']: message += f'{function}: ' for roleId in config['permission'][function]: roleId = str(roleId) if roleId not in roleIdMapping: message += f'{roleId}(角色已被删除), ' else: message += f'{roleId}({roleIdMapping[roleId]}), ' if len(config['permission'][function]) != 0: message = message[:-2] + '\n' else: message += '无\n' await reply(msg, message) elif args[0] == 'add': if len(args) != 3: await reply( msg, '参数错误\n权限添加帮助: .permission add <功能名称> <角色ID>') else: message = operationPermission(token, 'add', args[1], args[2]) if message is None: await reply( msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: await reply(msg, message) elif args[0] == 'del': if len(args) != 3: await reply( msg, '参数错误\n权限删除帮助: .permission del <功能名称> <角色ID>') else: message = operationPermission(token, 'del', args[1], args[2]) if message is None: await reply( msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: await reply(msg, message) else: message = '参数错误\n ' \ 'permission帮助:\n' \ ' - permission list: 显示权限对应的角色名称及ID\n' \ ' - permission add <功能名称> <角色ID>: 给予角色对应权限\n' \ ' - permission del <功能名称> <角色ID>: 移除角色对应权限\n' await reply(msg, message)
async def filter(msg: TextMsg, *args): token = getToken(msg.guild_id) if token is None: await reply(msg, '未配置token') else: adminPm = checkAdmin(token, int(msg.author_id)) if adminPm is None: await reply(msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') elif not adminPm: await reply(msg, '您无权使用该指令') else: if len(args) > 0: if args[0] == 'list': config = getServerConfig(token) if config is None: await reply( msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: message = '' for function in config['function']['receive']: message += f'{function}: ' if len(config['function']['receive'][function] ['filter']) == 0: message += '无\n' else: filterList = '' for filter in config['function']['receive'][ function]['filter']: filterList += f'{filter}, ' filterList = filterList[:-2] message += f'{filterList}\n' await reply(msg, message) elif args[0] == 'add': if len(args) != 3: await reply( msg, '参数错误\n过滤关键词添加帮助: .filter add <功能名称> <关键词>') else: message = operationFilter(token, 'add', args[1], args[2]) if message is None: await reply( msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: await reply(msg, message) elif args[0] == 'del': if len(args) != 3: await reply( msg, '参数错误\n过滤关键词移除帮助: .filter del <功能名称> <角色ID>') else: message = operationFilter(token, 'del', args[1], args[2]) if message is None: await reply( msg, '已获取token但未获取到配置文件, 请重试.\n若多次出现请尝试重新配置或联系管理') else: await reply(msg, message) else: message = '参数错误\n' \ 'filter帮助:\n ' \ ' - filter list: 显示各功能的过滤关键词\n' \ ' - filter add <功能名称> <角色ID>: 添加该功能的过滤关键词\n' \ ' - filter del <功能名称> <角色ID>: 移除该功能的过滤关键词\n' await reply(msg, message)
logger.setLevel(logging.INFO) handler = logging.FileHandler(filename='./persistence/discord' + str(datetime.datetime.now()) + '.log', encoding='utf-8', mode='w') handler.setFormatter( logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) if len(sys.argv) < 2: configfile = "./persistence/config.ini" else: configfile = sys.argv[1] try: getToken(filename=configfile) getCreds(filename=configfile) except: print("Config file invalid, creating a new one") base = "[token]\n\ token=\n\n\ [creds]\n\ username=\n\ password=\n\n\ Password is optional if using keyfile\n\ [logging]\n\ logfile=\n\n\ [keyfile]\n\ keyfile=\n\n\ [ownerid]\n\ ownerid="
'CLI for mPulse Query API. For more information about the API, please refer to https://developer.akamai.com/api/web_performance/mpulse_query/v2.html' ) parser.add_argument( '--config', help= 'mPulse configuration file containing the user\'s API key (deault=~/.mpulse)', default="~/.mpulse") parser.add_argument( '--section', help= 'Section within the config file containing the credentials (default=[mpulse])', default='mpulse') parser.add_argument('--api_key', help='API key of the app', required=True) parser.add_argument('--timer', help='The timer to report (default=page load time)', default='PageLoad') #gather up reminder parser.add_argument('args', nargs=argparse.REMAINDER) args = parser.parse_args() logger.debug('Configuration file: ' + args.config) logger.debug('Configuration section: ' + args.section) logger.debug(args) ## first create a security token token = config.getToken(args.config, args.section) logger.debug(token) ## now fire the API call getApiResponse(token, args)
pass if __name__ == "__main__": #Start DataBase engine engine = create_engine('sqlite:///db/app.db') Session = sessionmaker(bind=engine) Base.metadata.create_all(engine) #Create tables if empty db = Session() bot.db = db #Load all Cogs for this bot bot.add_cog(Admin(bot)) bot.add_cog(LobbyAdmin(bot)) bot.add_cog(Lobby(bot)) #Crashes program: bot.add_cog(Twitch(bot)) try: from RoleSync import RoleSync bot.add_cog(RoleSync(bot)) except: pass try: from VoiceRole import VoiceRole bot.add_cog(VoiceRole(bot)) except: pass try: bot.run(getToken()) except discord.LoginFailure: print("Login error.")
import discord from discord.ext import commands, tasks import aiohttp import asyncio from config import getToken from Labs import Labs from Webserver import Webserver from BrayPull import BrayPull from SheetPull import SheetPull from Lab import Lab bot = commands.Bot(command_prefix="^", case_insensitive=True) @bot.event async def on_ready(): print(f"Logged in as {bot.user}") await bot.change_presence(activity=discord.Game(name="Loading...")) if __name__ == "__main__": bot.add_cog(Labs(bot)) bot.add_cog(Webserver(bot)) #bot.add_cog(BrayPull(bot)) bot.add_cog(SheetPull(bot)) print("Bot starting") bot.run(getToken("./persistence/config.ini"))
#!/usr/bin/python3 # -*- coding: utf-8 -*- import telebot,os import config os.chdir(os.path.dirname(os.path.realpath(__file__))) if(config.getToken()==None): print("No token set for the bot. Please set a token in the config.py file.") exit(1) bot = telebot.TeleBot(config.getToken()) """ /start and /help message handler. Informing WIP, ofc. """ @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, "Thanks for checking Eve-Central Bot! Right now it is under construction, so you have to be patient. Cheers!") """ Polling for messages. """ while True: try: bot.polling(none_stop=True) except KeyboardInterrupt: print("Caught KeyboardInterrupt. Exiting...") exit() except Exception as e: traceback.print_tb(e.__traceback__)
import sys import requests import json import time import pandas as pd from matplotlib.pyplot import MultipleLocator import config import taskthread argv = sys.argv print(argv[1]) _os = "" token = config.getToken() url = config.getUrl() if (len(argv) > 2): _os = "$os='" + argv[2] + "' and" gstart = argv[1] #'2020-6-3' gend = time.strftime("%Y-%m-%d", time.localtime()) width = 0 def showResult(slist, helplist): nums = [] #人数 dates = [] #日期 hnums = [] #求助人数
else: action = lang = None if action: pass else: context.bot.send_message(chat_id=update.effective_chat.id, text='No actions') def imageHandler(update: Update, context: CallbackContext): print(update) for photo in update.message.photo: context.bot.send_photo(photo=photo.file_id, chat_id=update.effective_chat.id) bot_token = getToken() db = getDbName() + '.db' def main(): updater = Updater(token=bot_token, use_context=True) updater.dispatcher.add_handler(MessageHandler(Filters.photo, imageHandler)) updater.dispatcher.add_handler(MessageHandler(Filters.text, textHandler)) updater.dispatcher.add_handler(CommandHandler('start', startHandler)) updater.start_polling() updater.idle() if __name__ == '__main__':