async def on_member_update(self, before, after): # guild id guild_id = before.guild.id if not Utils.is_loaded("roledm", guild_id): return # all roles to listen select = f"select role_id from roledm_role where guild_id='{guild_id}'" fetched = database.fetch_all_line(select) for line in fetched: role_id = line[0] if (not Utils.has_role(before, role_id) and Utils.has_role(after, role_id)): # The member obtained the role logger("roledm::on_member_update", 'The member obtained the role') select = f"select message from roledm_message where guild_id='{guild_id}'and role_id='{role_id}' ;" fetched = database.fetch_one_line(select) if fetched: message = (fetched[0]).replace("$member", before.mention).replace( "$role", f"<@&{role_id}>") else: message = Utils.get_text( guild_id, 'welcome_no_message').format(before.mention) # send await before.send(message)
async def garden_dm(self, message): # message = dm ? if message.channel.type != discord.ChannelType.private: return # don't read a bot yourself included if message.author.bot: return # log for dm sql = f"select channel_id,guild_id from spy_log ;" fetched_log_channel = database.fetch_all_line(sql) # logger ("logs::garden_dm", f"fetched_log_channel: {fetched_log_channel}") if fetched_log_channel: for db_log_channel in fetched_log_channel: log_channel = await self.bot.fetch_channel( int(db_log_channel[0])) guild = log_channel.guild if (not message.author in guild.members): continue member = message.author colour = discord.Colour(0) colour = colour.from_rgb(225, 199, 255) embed = discord.Embed(colour=colour) embed.set_author(icon_url=member.avatar_url, name="DM by " + str(member) + " [" + str(member.id) + "]") embed.description = message.content embed.timestamp = datetime.utcnow() embed.set_footer(text=f"ID: {message.id}") try: await log_channel.send(content=None, embed=embed) except Exception as e: logger("logs::garden_dm", f" {type(e).__name__} - {e}") return
def login(self, *args): # print("login args:", args) cmd_dic = args[0] user_file_path = os.path.join(DB_PATH, cmd_dic["username"] + ".json") user_home_path = os.path.join(HOME_PATH, cmd_dic["username"]) if os.path.isfile(user_file_path): cmd_dic["exist"] = True # 向客户端发送用户存在状态 self.request.send(json.dumps(cmd_dic).encode('utf-8')) cmd_dic = json.loads(self.request.recv(1024).decode()) # 验证用户名密码 user_dic = Account().login(cmd_dic["username"], cmd_dic["password"]) if user_dic: self.username = cmd_dic["username"] self.home_path = user_home_path self.server_path = user_home_path self.home_size = user_dic.get("storage") cmd_dic["login"] = True cmd_dic["home_path"] = user_home_path # 向客户端发送用户登录状态 self.request.send(json.dumps(cmd_dic).encode('utf-8')) else: cmd_dic["exist"] = None self.request.send(json.dumps(cmd_dic).encode('utf-8')) logger("ftp_server", "LOGIN", "warning", "用户 %s 登录失败,该用户不存在" % cmd_dic["username"])
async def log(self, db, member, message, error, params=None): guild_id = message.channel.guild.id sql = f"select channel_id from {db} where guild_id='{guild_id}'" db_log_channel = database.fetch_one_line(sql) if not db_log_channel: # log_channel = message.channel return # if not log_channel don't log else: log_channel = await self.bot.fetch_channel(int(db_log_channel[0])) colour = discord.Colour(0) colour = colour.from_rgb(176, 255, 176) if error: colour = colour.from_rgb(255, 125, 125) embed = discord.Embed(colour=colour) embed.set_author(icon_url=member.avatar_url, name=str(member)) embed.description = message.content embed.timestamp = datetime.utcnow() embed.set_footer(text=f"ID: {message.id}") if params and "url_to_go" in params: embed.description = embed.description + "\njumpto: " + params[ "url_to_go"] try: await log_channel.send(content=None, embed=embed) except Exception as e: logger("logs::log", f" {type(e).__name__} - {e}")
async def reset_birthday(self, ctx, member: discord.Member = None): guild_id = ctx.guild.id error = False member = member or ctx.author if member is None: await ctx.send("Le paramètre <member> est obligatoire.") await ctx.message.add_reaction('❌') await self.logger.log('birthday_log', ctx.author, ctx.message, True) return sql = f"SELECT user_id FROM birthday_user WHERE user_id={member.id} and guild_id={ctx.guild.id}" member_in_db = database.fetch_one_line(sql) if not member_in_db: await ctx.send( Utils.get_text(ctx.guild.id, "error_user_not_found").format( member.mention, 'birthday_user')) return sql = f"DELETE FROM birthday_user WHERE user_id='{member.id}' and guild_id={ctx.guild.id} ;" try: database.execute_order(sql, []) except Exception as e: error = True await ctx.send( Utils.get_text(ctx.guild.id, 'error_database_writing')) logger("birthday::reset_birthday", f"{type(e).__name__} - {e}") await ctx.send( Utils.get_text(ctx.guild.id, 'birthday_reset').format(member.mention)) await self.logger.log('birthday_log', ctx.author, ctx.message, error)
async def set_birthday_channel(self, ctx, channel: discord.TextChannel = None): """Save channel where birthday will be wished. Param: channel ID""" guild_id = ctx.guild.id channel = channel or ctx.channel channel_id = channel.id sql = f"SELECT channel_id FROM birthday_channel WHERE guild_id='{guild_id}'" is_already_set = database.fetch_one_line(sql) if is_already_set: sql = f"UPDATE birthday_channel SET channel_id='{channel_id}' WHERE guild_id='{guild_id}'" else: sql = f"INSERT INTO birthday_channel VALUES ('{channel_id}', '{guild_id}') ;" try: database.execute_order(sql, []) except Exception as e: await ctx.send( Utils.get_text(ctx.guild.id, 'error_database_writing')) logger("birthday::set_birthday_channel", f"{type(e).__name__} - {e}") await ctx.send( Utils.get_text(ctx.guild.id, 'birthday_channel_set').format(f'<#{channel_id}>'))
async def edit_rule(self, ctx: commands.Context, emoji_text: str = None): if not emoji_text: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<emoji>')) await ctx.message.add_reaction('❌') return custom_emoji_id = Utils.is_custom_emoji(emoji_text) sql = f"SELECT * FROM rules_table WHERE (emoji_text='{emoji_text}' OR emoji_id='{custom_emoji_id}') and guild_id=?;" fetched = database.fetch_one_line(sql, [ctx.guild.id]) if not fetched: await ctx.send( Utils.get_text(ctx.guild.id, "rules_not_found").format(emoji_text)) await ctx.message.add_reaction('❌') return await ctx.send(Utils.get_text(ctx.guild.id, "ask_message")) msg = await self.bot.wait_for( 'message', check=lambda m: m.channel == ctx.channel and m.author == ctx.author ) message = msg.content sql = f"UPDATE rules_table SET rule=? WHERE (emoji_text='{emoji_text}' OR emoji_id='{custom_emoji_id}') and guild_id=?;" try: database.execute_order(sql, [message, ctx.guild.id]) await ctx.message.add_reaction('✅') except Exception as e: logger("rules::edit_rule", f"{type(e).__name__} - {e}") await ctx.send( Utils.get_text(ctx.guild.id, "rules_edited").format(emoji_text))
async def set_gallery_delay(self, ctx, delay: str = None): author = ctx.author guild_id = ctx.message.guild.id try: if not delay.isnumeric(): delay = Utils.parse_time(delay) type_delay = "gallery" select = ("select delay from config_delay" + " where " + f" `type_delay`=? and `guild_id`='{guild_id}'" + "") fetched = database.fetch_one_line(select, [type_delay]) if fetched: order = ("update config_delay" + " set `delay`=? " + " where " + f" `type_delay`=? and `guild_id`='{guild_id}'" + "") else: order = ("insert into config_delay" + " (`delay`, `type_delay`, `guild_id`) " + " values " + f" (?, ?, '{guild_id}')" + "") database.execute_order(order, [delay, type_delay]) await ctx.message.add_reaction('✅') except Exception as e: logger("gallery::set_gallery_delay", f" {type(e).__name__} - {e}") error = True await ctx.message.add_reaction('❌') await self.logger.log('config_log', author, ctx.message, error)
def create_host(self): """创建新的主机信息""" new_hostname = input("\033[34m请输入主机的地址:\033[0m").strip() if not self.host_dic.get(new_hostname): while True: new_host_port = input("\033[34m请输入主机的ssh端口号:\033[0m").strip() if new_host_port.isdigit(): new_host_username = input( "\033[34m请输入主机的登录用户名:\033[0m").strip() new_host_password = input( "\033[34m请输入主机的登录密码:\033[0m").strip() new_host_dic = { "hostname": new_hostname, "port": int(new_host_port), "username": new_host_username, "password": new_host_password } self.host_dic[new_hostname] = new_host_dic self.write_host_dic() # print("\033[33m主机 %s 信息已经保存。\033[0m\n" % new_hostname) logger("launcher", "info", "create_host", "主机 %s 信息已经保存。" % new_hostname) break else: print("\033[1;31m端口号应为 1-65535 的整数\033[0m") else: print("\033[1;31m主机 %s 已存在。\033[0m\n" % new_hostname)
async def send_token(self, ctx, member: discord.Member = None): """Send the token's link in a DM""" member = member or ctx.author guild_id = ctx.guild.id error = False try: colour = discord.Colour(0) url = Utils.get_text( guild_id, 'gallery_token') + await self.get_galerie_link( guild_id, member) sql = f"select message from galerie_message where guild_id='{guild_id}'" galerie_message = database.fetch_one_line(sql) if galerie_message: url = url + "\n\n" + galerie_message[0] colour = colour.from_rgb(170, 117, 79) icon_url = "https://cdn.discordapp.com/attachments/494812564086194177/597037745344348172/LotusBlanc.png" name = self.bot.user.display_name embed = discord.Embed(colour=colour) embed.set_author(icon_url=icon_url, name=name) embed.description = url embed.timestamp = datetime.utcnow() await member.send(content=None, embed=embed) await ctx.message.add_reaction('✅') except Exception as e: await ctx.message.channel.send( Utils.get_text(ctx.guild.id, 'error_user_disabled_PM').format( member.display_name)) logger("gallery::send_token", f" {type(e).__name__} - {e}") await ctx.message.add_reaction('❌') error = True await self.logger.log('galerie_log', ctx.author, ctx.message, error)
def put_file(self, host, cmd): """向远程主机上传文件""" operate, filename = cmd.split(" ") # print(operate, filename) transport = paramiko.Transport( (self.host_dic[host]["hostname"], self.host_dic[host]["port"])) try: transport.connect(username=self.host_dic[host]["username"], password=self.host_dic[host]["password"]) sftp = paramiko.SFTPClient.from_transport(transport) local_file_path = os.path.join(FILE_DIR_PATH, filename) host_file_path = '/home/' + self.host_dic[host][ "username"] + "/" + filename # 将 local_file_path 上传至服务器 host_file_path print("正在向主机 %s 上传文件 %s ,请等待..." % (host, filename)) sftp.put(local_file_path, host_file_path, callback=self.trans_size) # print("\n\033[33m文件 %s 已上传至主机 %s\033[0m" % (filename, host)) logger("launcher", "info", "put_file", "文件 %s 已上传至主机 %s" % (filename, host)) except Exception as e: # print("\033[1;31m主机 %s 执行时出错: %s\033[0m" % (host, e)) logger("launcher", "error", "put_file", "主机 %s 执行时出错: %s" % (host, e)) finally: transport.close()
async def set_do(self, ctx, type_do: str = None, do: str = None): guild_id = ctx.message.guild.id author = ctx.author if not type_do: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('**<type_do>**')) return if not do: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('**<do>**')) return error = False try: select = ("select do from config_do" + " where " + f" `type_do`=? and `guild_id`='{guild_id}'" + "") fetched = database.fetch_one_line(select, [type_do]) if fetched: order = ("update config_do" + " set `do`=? " + " where " + f" `type_do`=? and `guild_id`='{guild_id}'" + "") else: order = ("insert into config_do" + " (`do`, `type_do`, `guild_id`) " + " values " + f" (?, ?, '{guild_id}')" + "") database.execute_order(order, [do, type_do]) await ctx.message.add_reaction('✅') except Exception as e: logger("configuration::set_do", f" {type(e).__name__} - {e}") error = True await ctx.message.add_reaction('❌') await self.logger.log('config_log', author, ctx.message, error)
async def set_do_first_emoji(self, ctx: commands.Context, true_or_false: str): """ Toggle the first emoji for the timer """ guild_id = ctx.guild.id type_do = "first_emoji" do_first_emoji = (true_or_false.lower() == "true") select = "select do from config_do where type_do=? and guild_id=? ;" fetched = database.fetch_one_line(select, [type_do, guild_id]) if not fetched: order = "insert into config_do (do, type_do, guild_id) values (?, ?, ?) ;" else: order = "update config_do set do=? where type_do=? and guild_id=? ;" try: database.execute_order(order, [do_first_emoji, type_do, guild_id]) except Exception as e: logger("timer::set_do_first_emoji", f"{type(e).__name__} - {e}") return if (do_first_emoji): await ctx.send(Utils.get_text(guild_id, "timer_set_do_first_emoji")) else: await ctx.send( Utils.get_text(guild_id, "timer_set_do_first_emoji_not")) await ctx.message.delete(delay=0.5)
def processor_produce(): quantity=[220] core.logger(core.DEBUG,"Running processor produce") session,headers=core.email_simcompany_login() total_quantity=0 for q in quantity: total_quantity +=q chem_data=core.get_resource(session,headers,constants.CHEMICALS) silicon_data=core.get_resource(session,headers,constants.SILICON) transport_data=core.get_resource(session,headers,constants.TRANSPORT) chem_price=core.calculate_price(chem_data,total_quantity,constants.CHEMICALS) silicon_price=core.calculate_price(silicon_data,(total_quantity*4),constants.SILICON) transport_price=core.calculate_price(transport_data,total_quantity,constants.TRANSPORT) core.buy_resource(session,headers,total_quantity,0,chem_price,constants.CHEMICALS) core.buy_resource(session,headers,(total_quantity*4),0,silicon_price,constants.SILICON) core.buy_resource(session,headers,total_quantity,0,transport_price,constants.TRANSPORT) buildings=core.get_buildings(session,headers) for amount in quantity: for i in buildings: try: tmp=i['busy'] continue except KeyError: if i['name'] == "Electronics factory": bid=i['id'] core.produce(session,headers,bid,constants.PROCESSORS,amount)
async def remove_domain(self, ctx: commands.Context, domain: str = None): if not domain: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format("domain")) return sql = f"SELECT domain FROM source_domain WHERE guild_id='{ctx.guild.id}' ;" if domain not in [ domain[0] for domain in database.fetch_all_line(sql) ]: await ctx.send( Utils.get_text(ctx.guild.id, "source_domain_not_found").format(domain)) await ctx.message.add_reaction('❌') return sql = f"DELETE FROM source_domain WHERE domain='{domain}' and guild_id='{ctx.guild.id}' ;" try: database.execute_order(sql, []) await ctx.message.add_reaction('✅') except Exception as e: logger("source::remove_domain", f"{type(e).__name__} - {e}") await ctx.message.add_reaction('❌') return await ctx.send( Utils.get_text(ctx.guild.id, "source_domain_removed").format(domain))
async def do_load(self, ctx, *, cog: str): """ Load cogs for this guild """ author = ctx.author guild_id = ctx.guild.id if not cog: await ctx.message.add_reaction('❌') await ctx.send("Paramètre <cog> obligatoire.") return cog = cog.lower() try: select = ("select status " "from config_cog " + "where " + "cog=? " + " and " + "guild_id=? ;" + "") fetched = database.fetch_one_line(select, [cog, guild_id]) sql = "" if fetched: status = fetched[0] if status == 0: sql = "update config_cog set status=1 where cog=? and guild_id=? ;" else: sql = "insert into config_cog (`cog`, `guild_id`, `status`) values (?,?,1) ;" if len(sql): database.execute_order(sql, [cog, guild_id]) except Exception as e: await ctx.message.add_reaction('❌') logger("loader::do_load", f"{type(e).__name__} - {e}") else: await ctx.message.add_reaction('✅')
def oranges_produce(): core.logger(core.DEBUG,"Running function oranges_produce") quantity=[3830,3829] session,headers=core.email_simcompany_login() # ALL NECESSARY FOR PRODUCTION total_quantity=0 for q in quantity: total_quantity += q water_resource_data=core.get_resource(session,headers,constants.WATER) water_price=core.calculate_price(water_resource_data,(total_quantity*3),constants.WATER) seeds_resource_data=core.get_resource(session,headers,constants.SEEDS) seeds_price=core.calculate_price(seeds_resource_data,total_quantity,constants.SEEDS) core.buy_resource(session,headers,(total_quantity*3),0,water_price,constants.WATER) core.buy_resource(session,headers,total_quantity,0,seeds_price,constants.SEEDS) buildings=core.get_buildings(session,headers) if type(quantity) == list: for amount in quantity: for i in buildings: try: tmp=i['busy'] continue except KeyError: if i['name'] == "Plantation": bid=i['id'] core.produce(session,headers,bid,constants.ORANGES,amount)
async def update_welcomeuser(self, ctx): guild_id = ctx.message.guild.id member = ctx.author select = f"select role_id from welcome_role where guild_id='{guild_id}'" fetched_all = database.fetch_all_line(select) if not fetched_all: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_role_defined")) return for fetched in fetched_all: role_id = int(fetched[0]) # get the role role = ctx.guild.get_role(role_id) # write every member for member in role.members: # sql insert = ( "insert into welcome_user (`user_id`, `role_id`, `welcomed_at`, `guild_id`)" + f"values ('{member.id}', {role_id},{math.floor(time.time())}, '{guild_id}') ;" ) try: database.execute_order(insert) except Exception as e: logger("welcome::update_welcomeuser", f'{type(e).__name__} - {e}') await ctx.message.add_reaction('✅')
async def list_cogs_guild(self, ctx): """ Command which lists all loaded cogs for this guild """ author = ctx.author guild_id = ctx.guild.id all_loaded = "" for name in self.bot.cogs.keys(): cog = name.lower() try: select = ("select status " "from config_cog " + "where " + "cog=? " + " and " + "guild_id=? ;" + "") fetched = database.fetch_one_line(select, [cog, guild_id]) if (fetched and fetched[0] == 1) or (cog in [ "configuration", "help", "loader", "logs" ]): all_loaded += f"- **{name}**\n" except Exception as e: logger("loader::list_cogs_guild", f"{type(e).__name__} - {e}") if not len(all_loaded): all_loaded = "**NONE**" try: await ctx.send(all_loaded) except Exception as e: logger("loader::list_cogs_guild", f'{type(e).__name__} - {e}')
async def set_welcome_message(self, ctx, role: discord.Role = None): guild_id = ctx.message.guild.id member = ctx.author if not role: await ctx.message.add_reaction('❌') await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<role>')) return await ctx.send(Utils.get_text(ctx.guild.id, "ask_welcome_message")) check = lambda m: m.channel == ctx.channel and m.author == ctx.author msg = await self.bot.wait_for('message', check=check) message = msg.content sql = f"select message from welcome_message where guild_id='{guild_id}' and role_id={role.id}; " prev_galerie_message = database.fetch_one_line(sql) if not prev_galerie_message: sql = f"INSERT INTO welcome_message (`message`,`role_id`,`guild_id`) VALUES (?, {role.id},'{guild_id}') ;" else: sql = f"update welcome_message set message=? where guild_id='{guild_id}' and role_id={role.id} ;" logger("welcome::set_welcome_message", sql) try: database.execute_order(sql, [message]) except Exception as e: logger("welcome::set_welcome_message", f"{type(e).__name__} - {e}") await ctx.channel.send( Utils.get_text(ctx.guild.id, "display_new_message").format(message))
async def set_welcome(self, ctx, *, channel: discord.TextChannel = None): """ Set the welcome channel """ channel = channel or ctx.channel guild_id = ctx.guild.id error = False select = f"select * from welcome_channel where guild_id='{guild_id}' ;" fetched = database.fetch_one_line(select) if not fetched: sql = f"insert into welcome_channel values ('{channel.id}', '{guild_id}') ;" else: sql = f"update welcome_channel set channel_id='{channel.id}' where guild_id='{guild_id}' ;" try: database.execute_order(sql, []) except Exception as e: await ctx.channel.send( Utils.get_text(ctx.guild.id, "error_database_writing")) logger("welcome::set_welcome", f'{type(e).__name__} - {e}') error = True # Log my change if error: await ctx.message.add_reaction('❌') else: await ctx.message.add_reaction('✅')
async def set_welcome_role(self, ctx, *, role: discord.Role = None): """ Set welcome role """ guild_id = ctx.guild.id if not role: # error await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<role>')) await self.logger.log('nickname_log', ctx.author, ctx.message, True) return role_id = role.id select = f"select role_id from welcome_role where guild_id='{guild_id}' and role_id='{role_id}' ;" fetched = database.fetch_one_line(select) if fetched: sql = f"update welcome_role set role_id='{role_id}' where guild_id='{guild_id}' and role_id='{role_id}' ;" else: sql = f"insert into welcome_role values ('{role_id}', '{guild_id}') ;" error = False logger("welcome::set_welcome_role", sql) try: database.execute_order(sql, []) except Exception as e: error = True # Log my change if error: await ctx.message.add_reaction('❌') else: await ctx.message.add_reaction('✅')
async def on_ready(): logged_in_as = "Logged in as {0} [{1}]".format(bot.user.name, bot.user.id) discord_version = "Discord.py version {0}".format(discord.__version__) len_logged_in_as = len(logged_in_as) len_discord_version = len(discord_version) discord_version = discord_version + ( " " * (len_logged_in_as - len_discord_version)) dash = "----" + ("-" * len_logged_in_as) login = ("{0}\n" "| {1} |\n" "{0}\n" "| {2} |\n" "{0}\n").format(dash, logged_in_as, discord_version) print(login) try: await bot.change_presence(activity=discord.Game( name=botconfig.config['activity'])) except TypeError as type_err: logger("bot::on_ready", "Error TypeError : {}".format(type_err)) sys.exit(0) except Exception as e: logger("bot::on_ready", f"{type(e).__name__} - {e}") sys.exit(0) """
async def blacklist_domain(self, ctx: commands.Context, domain: str = None): if not domain: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format("domain")) return if "." in domain: await ctx.send(Utils.get_text(ctx.guild.id, "source_wrong_format")) return sql = f"SELECT domain FROM source_domain WHERE guild_id='{ctx.guild.id}' ;" if domain in [domain[0] for domain in database.fetch_all_line(sql)]: await ctx.send( Utils.get_text( ctx.guild.id, "source_domain_already_blacklisted").format(domain)) await ctx.message.add_reaction('❌') return sql = f"INSERT INTO source_domain VALUES ('{domain}', '{ctx.guild.id}') ;" try: database.execute_order(sql, []) await ctx.message.add_reaction('✅') except Exception as e: logger("source::blacklist_domain", f"{type(e).__name__} - {e}") await ctx.message.add_reaction('❌') return await ctx.send( Utils.get_text(ctx.guild.id, "source_domain_blacklisted").format(domain))
async def update_nickname(self, ctx): author = ctx.author guild_id = ctx.guild.id try: for member in ctx.guild.members: if member.nick: select = ( f"select nickname from nickname_current" + f" where guild_id='{guild_id}' and member_id='{member.id}' ;" ) fetched = database.fetch_one_line(select) sql = "" if not fetched: sql = ( f"insert into nickname_current values ('{member.id}', " + f" '{guild_id}' , '{member.nick}') ;") elif not member.nick == fetched[0]: # Impossibru sql = ( f"update nickname_current set nickname='{member.nick}'" + f" where guild_id='{guild_id}' and member_id='{member.id}' ;" ) if len(sql): database.execute_order(sql) await ctx.send(Utils.get_text(ctx.guild.id, "nickname_updated")) except Exception as e: await ctx.send( Utils.get_text(ctx.guild.id, "error_occured").format(f"{type(e).__name__}", f"{e}")) logger("nickname::update_nickname", f"{type(e).__name__} - {e}")
async def edit_message_turing(self, ctx, message_id: int = None): guild_id = ctx.message.guild.id author = ctx.author if not message_id: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<messageID>')) return error = False try: message = await self.get_message_general(ctx, message_id) if message: old_content_title = await ctx.send( Utils.get_text(ctx.guild.id, "turing_old_message")) old_content = await ctx.send(message.content) ask = await ctx.send( Utils.get_text(ctx.guild.id, "ask_message")) check = lambda m: m.channel == ctx.channel and m.author == ctx.author msg = await self.bot.wait_for('message', check=check) new_content = msg.content await message.edit(content=new_content) await ctx.message.delete(delay=2) await old_content_title.delete(delay=2) await old_content.delete(delay=2) await ask.delete(delay=2) await msg.delete(delay=2) else: await ctx.send( Utils.get_text(ctx.guild.id, "error_message_not_found")) error = True # await ctx.message.delete (delay=2) except Exception as e: logger("turing::edit_message_turing", f" {type(e).__name__} - {e}") error = True await self.logger.log('spy_log', author, ctx.message, error)
async def set_first_emoji(self, ctx: commands.Context, emoji_input: str): """ Set the first emoji for the timer """ guild_id = ctx.guild.id try: emoji = await Utils.get_emoji(ctx, emoji_input) except Exception as e: logger("timer::set_first_emoji", f"{type(e).__name__} - {e}") await ctx.send( Utils.get_text(guild_id, "timer_not_emoji").format(emoji_input)) return select = "select emoji from timer_first_emoji where guild_id=? ;" fetched = database.fetch_one_line(select, [guild_id]) if not fetched: order = "insert into timer_first_emoji (emoji, guild_id) values (?, ?) ;" else: order = "update timer_first_emoji set emoji=? where guild_id=? ;" try: database.execute_order(order, [str(emoji), guild_id]) except Exception as e: logger("timer::set_first_emoji", f"{type(e).__name__} - {e}") return await ctx.send( Utils.get_text(guild_id, "timer_set_first_emoji").format(str(emoji))) await ctx.message.delete(delay=0.5)
async def react_to_message(self, ctx, message_id, emoji, react_type): guild_id = ctx.message.guild.id author = ctx.author if not message_id: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<messageID>')) return if not emoji: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<emoji>')) return error = False try: message = await self.get_message_general(ctx, message_id) if message: if react_type == "add": await message.add_reaction(emoji) else: await message.remove_reaction(emoji, self.bot.user) else: await ctx.send( Utils.get_text(ctx.guild.id, "error_message_not_found")) error = True # await ctx.message.delete (delay=2) except Exception as e: logger("turing::react_to_message", f" {type(e).__name__} - {e}") error = True await self.logger.log('spy_log', author, ctx.message, error, {"url_to_go": message.jump_url})
async def say_spy_log(self, ctx, channel: discord.TextChannel = None): guild_id = ctx.message.guild.id author = ctx.author if not channel: await ctx.send( Utils.get_text(ctx.guild.id, "error_no_parameter").format('<Channel>')) return error = False try: ask = await ctx.send( Utils.get_text(ctx.guild.id, "turing_ask_message")) check = lambda m: m.channel == ctx.channel and m.author == ctx.author msg = await self.bot.wait_for('message', check=check) message = msg.content await channel.send(message) await ctx.message.delete(delay=2) await ask.delete(delay=2) await msg.delete(delay=2) except Exception as e: logger("turing::say_spy_log", f" {type(e).__name__} - {e}") error = True await self.logger.log('spy_log', author, ctx.message, error) if message: await self.logger.log('spy_log', author, msg, error)
async def set_utip_delay(self, ctx): guild_id = ctx.message.guild.id author = ctx.author await ctx.send( "Entrez le délai durant lequel le membre garde le rôle : ") check = lambda m: m.channel == ctx.channel and m.author == ctx.author msg = await self.bot.wait_for('message', check=check) message = msg.content sql = f"select delay from config_delay where guild_id='{guild_id}' and type_delay='utip_role' ;" try: delay = Utils.parse_time(message) except Exception as e: await ctx.message.add_reaction('❌') await ctx.channel.send( Utils.get_text(ctx.guild.id, "utip_delay_error").format(message)) return prev_galerie_delay = database.fetch_one_line(sql) if not prev_galerie_delay: sql = f"insert into config_delay (`delay`, `type_delay`, `guild_id`) values (?, 'utip_role', '{guild_id}')" else: sql = f"update config_delay set delay=? where guild_id='{guild_id}' and type_delay='utip_role' ;" try: database.execute_order(sql, [delay]) except Exception as e: logger("utip::set_utip_delay", f"{type(e).__name__} - {e}") await ctx.message.add_reaction('❌') else: await ctx.message.add_reaction('✅')
def setUpdateRequest(thedevice, nbTime=1): """ set the device states to be updated Args: thedevice: current device """ core.logger(traceLog = u"Device \"%s\" has %s update requests stacked" % (thedevice.name,nbTime)) indigo.activePlugin._requestedUpdate[thedevice.id]=nbTime
def _run(self): core.logger(traceLog = u"time ellapsed for dialog timer \"%s\"" % (self.timername)) self.timeEllapsed = True if self.initialinterval>0: self._timer = Timer(self.initialinterval, self._run) self.initialinterval=0 else: self._timer = Timer(self.interval, self._run) self._timer.start()
def changeInterval(self, interval): """ Change interval value - restart the timer to take the new value in account Args: interval: interval in seconds """ self.interval = interval core.logger(traceLog = u"restarting with new timing value %s for dialog timer \"%s\"" % (interval, self.timername)) self._timer.cancel() self._run()
def startAction(thedevice, theaction): """ Check if the device is already in the required state - transform toggle in on or off Args: thedevice: current device theaction: indigo action Returns: None or action to provide """ theactionid = theaction.deviceAction core.logger(traceLog = u"requesting device \"%s\" action %s" % (thedevice.name,_kDimmerRelayActionDict[theactionid])) # work on toggling if theactionid == indigo.kDimmerRelayAction.Toggle: if thedevice.states['onOffState']: theactionid = indigo.kDimmerRelayAction.TurnOff else: theactionid = indigo.kDimmerRelayAction.TurnOn # test if needed if (theactionid == indigo.kDimmerRelayAction.TurnOn) and (thedevice.states['onOffState']): core.logger(msgLog= u"device %s is already on" % (thedevice.name)) return None if (theactionid == indigo.kDimmerRelayAction.TurnOff) and not(thedevice.states['onOffState']): core.logger(msgLog = u"device %s is already off" % (thedevice.name)) return None # go for the action core.logger(msgLog = u"sent device \"%s\" action %s " % (thedevice.name,_kDimmerRelayActionDict[theactionid])) return theactionid
def sleepNext(thetime): """ Calculate sleep time according main dialog pace Args: thetime: time in seconds between two dialog calls """ nextdelay = thetime - (time.time() - indigo.activePlugin.wakeup) nextdelay = round(nextdelay,2) if nextdelay < 1: nextdelay = 0.5 core.logger(traceLog = u"going to sleep for %s seconds" % (nextdelay)) indigo.activePlugin.sleep(nextdelay)
def isUpdateRequested(thedevice): """ Test is the device states need to be updated Args: thedevice: current device Returns: True is updateRequested """ if thedevice.id in indigo.activePlugin._requestedUpdate: if indigo.activePlugin._requestedUpdate[thedevice.id]>0: indigo.activePlugin._requestedUpdate[thedevice.id] = indigo.activePlugin._requestedUpdate[thedevice.id]-1 core.logger(traceLog = u"Device \"%s\" is going to process an update request" % (thedevice.name)) return True return False
def __init__(self, timername, interval, initialinterval=0): """ Constructor Args: timername : name of the timer (for logging use) interval: interval in seconds initialinterval : first interval in seconds (ignored if 0) Returns: dialogTimer class instance """ self._timer = None self.timername = timername self.initialinterval = initialinterval self.interval = interval self.timeEllapsed = True core.logger(traceLog = u"initiating dialog timer \"%s\" on a %s seconds pace" % (self.timername, interval)) self._run()
def __del__(self): core.logger(traceLog = u'deleting dialog timer "%s"' % (self.timername)) self._timer.cancel()
def run(ascript, akeys = None, errorHandling = None): """ Calls applescript script and returns the result as a python dictionnary Args: ascript: applescript as text akeys: list of keys, ordered the same way that output data of the applescript, or None errorHandling : a compiled regular expression matching errors to ignore or number of retry (integer) or None if no special management Returns: python dictionnay of the states names and values, or unicode string returned by the script is akeys is None, or None if error """ osaname = ascript.splitlines()[0] core.logger(traceRaw = u"going to call applescript %s" % (ascript),traceLog = u"going to call applescript %s" % (osaname)) osa = subprocess.Popen(['osascript','-e',ascript], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) indigo.activePlugin.sleep(0.25) (osavalues, osaerror) = osa.communicate() # error management if len(osaerror)>0: osaerror=osaerror[:-1].decode('utf-8') # test if error if errorHandling is None: core.logger(traceLog="no error handling", errLog = u"applescript %s failed because %s" % (osaname, osaerror)) return None else: core.logger(traceLog = u"applescript %s error handling %s because %s" % (osaname, type(errorHandling), osaerror)) if type(errorHandling) is int: # test if dictionnary exists if osaname in indigo.activePlugin._retryLog: indigo.activePlugin._retryLog[osaname]=indigo.activePlugin._retryLog[osaname]+1 if indigo.activePlugin._retryLog[osaname] >= errorHandling: core.logger(errLog = u"applescript %s failed after %s retry because %s" % (osaname, indigo.activePlugin._retryLog[osaname],osaerror)) return None else: indigo.activePlugin._retryLog[osaname]=1 indigo.activePlugin._errorMsg[osaname]= osaerror core.logger(traceLog = u"applescript %s failed %s time" % (osaname, indigo.activePlugin._retryLog[osaname])) else: if errorHandling.search(osaerror) is None: core.logger(errLog = u"applescript %s failed because %s" % (osaname ,osaerror)) else: core.logger(msgLog = u"warning on applescript %s : %s" % (osaname, osaerror), isMain=False) # continue the process with a dummy value osavalues="\n" else: # a success sets the # retries to 0 if type(errorHandling) is int: if osaname in indigo.activePlugin._retryLog: if (indigo.activePlugin._retryLog[osaname]>0) and (indigo.activePlugin._retryLog[osaname]<errorHandling): core.logger(msgLog = u"warning on applescript %s : %s" % (osaname, indigo.activePlugin._errorMsg[osaname]), isMain=False) indigo.activePlugin._retryLog[osaname]=0 indigo.activePlugin._errorMsg[osaname]="" # return value without error if akeys is None: # return text if no keys osavalues = core.strutf8(osavalues[:-1]) else: # return list of values osavalues = dict(zip(akeys,(osavalues[:-1]).split("||"))) for thekey,thevalue in osavalues.iteritems(): osavalues[thekey] = core.strutf8(thevalue) core.logger(traceRaw = u"returned from applescript: %s" % (osavalues),traceLog = u"returned from applescript %s" % (osaname)) return osavalues
def numbered_for_tratk(show, season, episode): """ Devuelve la temporada y episodio convertido para que se marque correctamente en tratk.tv :param show: Nombre de la serie a comprobar :type show: str :param season: Temporada que devuelve el scrapper :type season: int :param episode: Episodio que devuelve el scrapper :type episode: int :return: season, episode :rtype: int, int """ logger.info("pelisalacarta.channels.animeflv numbered_for_tratk") show = show.lower() new_season = season new_episode = episode dict_series = {} name_file = os.path.splitext(os.path.basename(__file__))[0] fname = os.path.join(config.get_data_path(), "settings_channels", name_file + "_data.json") if os.path.isfile(fname): data = "" try: with open(fname, "r") as f: for line in f: data += line except EnvironmentError: logger("ERROR al leer el archivo: {0}".format(fname)) json_data = jsontools.load_json(data) if 'TVSHOW_RENUMBER' in json_data: dict_series = json_data['TVSHOW_RENUMBER'] # ponemos en minusculas el key, ya que previamente hemos hecho lo mismo con show. for key in dict_series.keys(): new_key = key.lower() if new_key != key: dict_series[new_key] = dict_series[key] del dict_series[key] if show in dict_series: logger.info("ha encontrado algo: {0}".format(dict_series[show])) if len(dict_series[show]['season_episode']) > 1: for row in dict_series[show]['season_episode']: if new_episode > row[1]: new_episode -= row[1] new_season = row[0] break else: new_season = dict_series[show]['season_episode'][0][0] new_episode += dict_series[show]['season_episode'][0][1] logger.info("pelisalacarta.channels.animeflv numbered_for_tratk: {0}:{1}".format(new_season, new_episode)) return new_season, new_episode
def __del__(self): core.logger(traceLog = u"deleting dialog timer \"%s\"" % (self.timername)) self._timer.cancel()
def doNow(self): """ Stop the current timing and set isTime to true """ core.logger(traceLog = u"forced time ellapsed for dialog timer \"%s\"" % (self.timername)) self._timer.cancel() self._run()
def run(pscript, rule=None, akeys=None): """ Calls shell script and returns the result Args: pscript: shell script as text rule: separator string, or a compiled regular expression with a group per data or list of integer tupples (firstchar,lastchar) to cut the string (trim will be applied), or None for no action on text akeys: list of keys, ordered the same way that output data of the shell, or None Returns: python dictionnay of the states names and values, or unicode string returned by the script is akeys is None, or None if error """ logscript=(pscript.split(u'|'))[0] core.logger(traceRaw = u'going to call shell %s' % (pscript), traceLog = u'going to call shell %s...' % (logscript)) p = subprocess.Popen(pscript, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, close_fds=True) indigo.activePlugin.sleep(0.1) (pvalues, perror) = p.communicate() if len(perror)>0: # test if error core.logger(errLog = u'shell script failed because %s' % (perror.decode('utf-8'))) return None if akeys is None: # return text if no keys returnvalue = pvalues.strip().decode('utf-8') elif rule is None: returnvalue= {akeys[0]: pvalues.strip().decode('utf-8')} elif type(rule) is list: # split using position returnvalue = {} for thekey,(firstchar,lastchar) in zip(akeys,rule): returnvalue[thekey] = core.strutf8(pvalues[firstchar:lastchar].strip()) elif type(rule)is str: # just use split returnvalue = dict(zip(akeys,pvalues.split(rule))) for thekey,thevalue in pvalues.iteritems(): returnvalue[thekey] = core.strutf8(thevalue.strip()) else: # split using regex returnvalue = {} try: for thekey,thevalue in zip(akeys,rule.match(pvalues).groups()): returnvalue[thekey] = core.strutf8(thevalue.strip()) except: for thekey in akeys: returnvalue[thekey]='' core.logger(traceRaw = u'returned from shell: %s' % (returnvalue), traceLog = u'returned from shell %s...' % (logscript)) return returnvalue