async def graph(msg, mobj): """ Do a 2D-plot of a user's given function Ex1: !graph cos(x)*10 Ex2: !graph cos(x)*10, xmax=10, xmin=-7 """ s = { 'xmax': 10.0, 'xmin': -10.0, 'ymax': 10.0, 'ymin': -10.0, } fname = bot_data("{}.png".format(mobj.author.id)) try: firstp = msg.split(",") # seperate equation from additional args func = firstp[0] if len(firstp) > 1: for p in firstp[1:]: arg, val = p.strip().split("=") if arg in s.keys(): s[arg] = float(val) else: return await client.send_message(mobj.channel, "Invalid arguments") if not all([isinstance(x, float) for x in s.values()]): return await client.send_message(mobj.channel, "Invalid arguments") graph = create_plot(monkey_patch_function(sympify(func)), s) graph.save(fname) await client.send_file(mobj.channel, fname) f_remove(fname) return except Exception as ex: logger("!graph: {}".format(ex)) return await client.send_message(mobj.channel, "Failed to render graph")
async def calculus(msg, mobj, lam, col): """ Base function to perform some kind of calculus :lam is the type of operation we want, should be a lambda function :col is the color of the plot we want to have """ s = { 'xmax': 10.0, 'xmin': -10.0, 'ymax': 10.0, 'ymin': -10.0, } fname = bot_data("{}.png".format(mobj.author.id)) try: firstp = msg.split(",") func = firstp[0] expr = monkey_patch_function(sympify(func)) var = list(expr.free_symbols)[0] graph = create_plot(expr, s) graph.extend(create_plot(lam(expr), s, color=col)) graph.save(fname) await client.send_file(mobj.channel, fname) f_remove(fname) return except Exception as ex: logger("!calculus: {}".format(ex)) return await client.send_message(mobj.channel, "Failed to render graph")
async def graphc(msg, mobj): """ Graph a complex equation (using mpmath functions and plotting) Equations should map to the complex domain Ex: !complex gamma(x) """ fname = bot_data("{}.png".format(mobj.author.id)) try: firstp = msg.split(",") func = firstp[0] expr = sympify(func) var = list(expr.free_symbols)[0] lamb = lambdify(var, monkey_patch_function(sympify(func)), modules=["mpmath"]) cplot(lamb, points=sample_size, file=fname) await client.send_file(mobj.channel, fname) f_remove(fname) return except Exception as ex: logger("!graphc: {}".format(ex)) return await client.send_message(mobj.channel, "Failed to render graph")
async def matrix(msg, mobj): """ Interpret a user string, convert it to a list and graph it as a matrix Uses ast.literal_eval to parse input into a list """ fname = bot_data("{}.png".format(mobj.author.id)) try: list_input = literal_eval(msg) if not isinstance(list_input, list): raise ValueError("Not a list") m = np_matrix(list_input) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_aspect('equal') plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean) plt.colorbar() plt.savefig(fname) await client.send_file(mobj.channel, fname) f_remove(fname) return except Exception as ex: logger("!matrix: {}".format(ex)) return await client.send_message(mobj.channel, "Failed to render graph")
async def upload_doc(message: types.Message): logging.info("/upload_doc command sent from user {0}({1})".format( message.from_user.full_name, message.from_user.id)) if message.from_user.id == AGENT_ID: name = message.document.file_name file_id = getattr(message, 'document').file_id uploader = act.statements[AGENT_ID]["uploader"] db.add_file(file_id, name, db.get_user_info(uploader)[3], db.get_user_info(uploader)[5], act.semester(uploader), act.currentDiscipline(uploader), act.currentFolder(uploader), uploader) report = f'Successfully uploaded by {message.from_user.full_name}({uploader})\nand saved to DB file "{name}"' logging.info(report) await bot.send_message(AGENT_ID, report) await bot.send_message(uploader, "Загрузка успешно завершена!") act.reset(uploader) act.reset(message.from_user.id) await message.answer("Загрузка успешно завершена!") if act.isUploadMode(message.from_user.id) and (act.semester( message.from_user.id) != 0) and (act.currentDiscipline( message.from_user.id) != "") and (act.currentFolder( message.from_user.id)) != "" and db.subscriber_exists( message.from_user.id): document_id = message.document.file_id name = message.document.file_name if db.file_exists(name, act.currentDiscipline(message.from_user.id), act.currentFolder(message.from_user.id)): await message.answer("Такой файл уже существует!") act.reset(message.from_user.id) return try: file_info = await bot.get_file(document_id) except Exception as e: # Обход ограничения на размер файла print(e) await message.forward(AGENT_ID) act.reset(AGENT_ID) act.statements[AGENT_ID]["uploader"] = message.from_user.id await upload_big() return fi = file_info.file_path await bot.download_file(fi, name) with open(name, 'rb') as file: try: msg = await bot.send_document(AGENT_ID, file, disable_notification=True) file_id = getattr(msg, 'document').file_id db.add_file(file_id, name, db.get_user_info(message.from_user.id)[3], db.get_user_info(message.from_user.id)[5], act.semester(message.from_user.id), act.currentDiscipline(message.from_user.id), act.currentFolder(message.from_user.id), message.from_user.id) report = f'Successfully uploaded by {message.from_user.full_name}({message.from_user.id})\nand saved to DB file "{name}"' logging.info(report) await bot.send_message(AGENT_ID, report) act.reset(message.from_user.id) await message.answer("Загрузка успешно завершена!") except Exception as e: logging.error('Couldn\'t upload {}. Error is {}'.format( name, e)) act.reset(message.from_user.id) return f_remove(name) # удаляем файл с устройства после завершения работы else: await message.answer("Не соблюдены все условия!")