def bili(update, context): try: try: index = str(random.randint(1, 50)) res = requests.get( "https://api.bilibili.com/x/web-interface/popular?ps=1&pn=" + index) json_res = json.loads(res.text) title = json_res["data"]["list"][0]["title"] pic = json_res["data"]["list"][0]["pic"] up = json_res["data"]["list"][0]["owner"]["name"] link = json_res["data"]["list"][0]["short_link"] bv = json_res["data"]["list"][0]["bvid"] localtime = time.asctime(time.localtime(time.time())) user = update.effective_user.name + ":\n" text = user + '北京时间:' + localtime + "\n哔哩哔哩随机热门第" + index + ":" \ + "\n视频标题:" + title \ + "\nUP主:" + up \ + "\nBV号:" + bv \ + "\n视频链接:" + link context.bot.send_message(chat_id=update.effective_chat.id, text=text) info("bili模块:" + text) context.bot.send_photo(chat_id=update.effective_chat.id, photo=pic) info("bili模块:" + user + pic) except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) context.bot.send_message(chat_id=update.effective_chat.id, text=text) error("bili模块:" + text) except: error("bili模块异常")
def stock_list_mine(update: Update): try: query = update.callback_query user_id = update.effective_user.id stocks = sql_funcs.sql_select_all_mine(user_id) if stocks is None: user = update.effective_user.name + ":\n" warning("股票模块-自选功能-股票选择器:" + update.effective_user.name + ":数据库中无自选股") query.bot.send_message(chat_id=update.effective_chat.id, text=user + "数据库内没有您的自选数据") return False else: keyboard = [] for i in stocks: describe = i[0] + "(股票代码" + i[1] + ")" keyboard.append( [InlineKeyboardButton(describe, callback_data=i[1])]) reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "请选择股票", reply_markup=reply_markup, ) return True except: error("股票模块-自选模块-股票选择器异常") return False
def stock_func(update: Update, _: CallbackContext) -> int: try: query = update.callback_query query.answer() query.delete_message() if query.data == "自选": info("股票模块-功能选择器:" + update.effective_user.name + "选择了自选功能") keyboard = [[ InlineKeyboardButton("添加自选", callback_data='添加自选'), InlineKeyboardButton("删除自选", callback_data='删除自选'), ], [InlineKeyboardButton("查看自选", callback_data='查看自选')], [ InlineKeyboardButton("列出全部自选", callback_data='列出全部自选') ]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "请选择功能", reply_markup=reply_markup, ) return STOCK_MINE elif query.data == "搜索": user = update.effective_user.name + ":\n" info("股票模块-功能选择器:" + update.effective_user.name + "选择了搜索功能") query.bot.send_message(chat_id=update.effective_chat.id, text=user + "请输入搜索词") return STOCK_SEARCH except: error("股票模块-自选功能选择器异常") return ConversationHandler.END
def sentence_input(update: Update, _: CallbackContext) -> int: try: keyboard = [[ InlineKeyboardButton("动画", callback_data='a'), InlineKeyboardButton("漫画", callback_data='b'), InlineKeyboardButton("游戏", callback_data='c'), InlineKeyboardButton("文学", callback_data='d'), ], [ InlineKeyboardButton("原创", callback_data='e'), InlineKeyboardButton("网络", callback_data='f'), InlineKeyboardButton("其他", callback_data='g'), InlineKeyboardButton("影视", callback_data='h'), ], [ InlineKeyboardButton("诗词", callback_data='i'), InlineKeyboardButton("网易云", callback_data='j'), InlineKeyboardButton("哲学", callback_data='k'), InlineKeyboardButton("抖机灵", callback_data='l'), ]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" text = user + '请选择类型' info("一言模块:" + text) update.message.reply_text( text, reply_markup=reply_markup, ) except: error("一言模块-类型选择器异常") return SENTENCE
def log_management(update: Update, _: CallbackContext): try: query = update.callback_query query.answer() query.delete_message() type = query.data if type == "完整日志": compress_file("logs/logs_full.zip", "logs/full") file = open("logs/logs_full.zip", "rb") query.bot.send_document(chat_id=update.effective_chat.id, document=file) elif type == "信息日志": compress_file("logs/logs_info.zip", "logs/info") file = open("logs/logs_info.zip", "rb") query.bot.send_document(chat_id=update.effective_chat.id, document=file) elif type == "警告日志": compress_file("logs/logs_warning.zip", "logs/warning") file = open("logs/logs_warning.zip", "rb") query.bot.send_document(chat_id=update.effective_chat.id, document=file) elif type == "错误日志": compress_file("logs/logs_error.zip", "logs/error") file = open("logs/logs_error.zip", "rb") query.bot.send_document(chat_id=update.effective_chat.id, document=file) return ConversationHandler.END except Exception as e: error("日志管理模块异常:" + str(e)) return ConversationHandler.END
async def emulate(self, event: dict) -> typing.Union[dict, str]: """ Process all signals from IRIS CM. :param event: New signal :return: "ok" (if possible) """ logger.debug("Event: {event}", event=event) if event is None: return {"response": "error", "error_code": NO_DATA} if event.get("secret") != self.secret: return {"response": "error", "error_code": INVALID_DATA} if event.get("user_id") != self.user_id: return {"response": "error", "error_code": INVALID_DATA} try: task = (await self._processor(event)) if task is not None: return task except Exception as e: processing = await self.error_processor(e, event) if processing is False: logger.error(traceback.format_exc(limit=5)) return traceback.format_exc(limit=5) if processing is not None: return processing return {"response": "ok"}
def start(update: Update, context): try: user = update.effective_user.name + ":\n" info("用户:" + update.effective_user.name + "开始了与机器人的交流") context.bot.send_message(chat_id=update.effective_chat.id, text=user + "欢迎使用Utopia机器人,请使用 /help 查看全部指令") except: error("无法发送开始信息,请检查网络")
async def subscribe_signals(event: types.SubscribeSignals): uid = event.object.chat try: await abstract_bind(uid, event.object.text, event.message.date, event.message.conversation_message_id) await db.chats.change(uid, is_duty=True) except (BaseORMException, Exception) as e: logger.error(e) return {"response": "error", "error_code": CANT_BIND_CHAT}
def get_me(update, context): try: user_id = update.effective_user.id user_name = update.effective_user.name info("用户名为" + user_name + "的用户获取了他的ID:" + str(user_id)) text = user_name + ":\n" + "您的ID为" + str(user_id) context.bot.send_message(chat_id=update.effective_chat.id, text=text) except Exception as e: error("获取ID模块异常:" + str(e))
def load_values() -> Optional[dict]: copy = default_data.copy() default_data.clear() try: with open(SETTINGS_PATH) as file: default_data.update(**json.loads(file.read())) return default_data except FileNotFoundError: logger.error("Can't find file \"settings.json\"! " "Reload script to recreate it.") return recreate(copy)
def setu(update: Update, _: CallbackContext) -> None: try: query = update.callback_query query.answer() query.delete_message() url = "" r18 = 0 if query.data == "R18": r18 = 1 info("涩图模块:R18选择:是") else: info("涩图模块:R18选择:否") try: res = requests.get("https://api.lolicon.app/setu/?r18=" + str(r18) + "&apikey=" + config.setu_Token) json_str = json.loads(res.text) if json_str['code'] == 401: user = update.effective_user.name + ":\n" text = user + "API接口超过调用限制(每令牌每天限制300)或API令牌被封禁" warning("涩图模块" + text) query.bot.send_message(chat_id=update.effective_chat.id, text=text) url = json_str['data'][0]['url'] author = json_str['data'][0]['author'] pid = json_str['data'][0]['pid'] title = json_str['data'][0]['title'] is_r = "否" if r18 != 0: is_r = "是" user = update.effective_user.name + ":\n" text = user + "图片信息:\n" \ "作者:" + str(author) \ + "\n图片PID:" + str(pid) \ + "\n图片标题:" + str(title) \ + "\n是否R18:" + is_r info("涩图模块:" + text) query.bot.send_message(chat_id=update.effective_chat.id, text=text) info("涩图模块:发送图片" + url) query.bot.send_photo(chat_id=update.effective_chat.id, photo=url) except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) + "\n请自行访问链接:" + url error("涩图模块:" + text) query.bot.send_message(chat_id=update.effective_chat.id, text=text) except: error("涩图模块-涩图发送方法异常") return ConversationHandler.END
def stock_input(update: Update, _: CallbackContext) -> int: try: keyboard = [[ InlineKeyboardButton("自选", callback_data='自选'), InlineKeyboardButton("搜索", callback_data='搜索'), ]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" info("股票模块-方法选择器:" + update.effective_user.name + "开始了股票功能") update.message.reply_text( user + '请选择方法', reply_markup=reply_markup, ) except: error("股票模块-方法选择器异常") return STOCK_FUNC
def setu_input(update: Update, _: CallbackContext): try: keyboard = [[ InlineKeyboardButton("R18", callback_data='R18'), InlineKeyboardButton("非R18", callback_data='非R18'), ]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name + ":\n" text = user + '请选择您需要的是R18还是非R18涩图' info("涩图模块:" + text) update.message.reply_text( text, reply_markup=reply_markup, ) except: error("涩图模块-R18选择器异常") return SETU
def admin(update: Update, _: CallbackContext) -> None: try: query = update.callback_query query.answer() query.delete_message() type = query.data if type == "数据库": keyboard = [[ InlineKeyboardButton("获取数据库信息", callback_data='获取数据库信息') ], [InlineKeyboardButton("重置数据库", callback_data='重置数据库')]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name text = user + ":\n" + '请选择数据库管理功能' info("管理员模块:一名管理员" + user + "选择了数据库管理功能") query.bot.send_message( chat_id=update.effective_chat.id, text=text, reply_markup=reply_markup, ) return DATABASE elif type == "日志": keyboard = [ [InlineKeyboardButton("完整日志", callback_data='完整日志')], [InlineKeyboardButton("信息日志", callback_data='信息日志')], [InlineKeyboardButton("警告日志", callback_data='警告日志')], [InlineKeyboardButton("错误日志", callback_data='错误日志')] ] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name text = user + ":\n" + '请选择日志类型功能' info("管理员模块:一名管理员" + user + "选择了日志管理功能") query.bot.send_message( chat_id=update.effective_chat.id, text=text, reply_markup=reply_markup, ) return LOG except Exception as e: error("管理员模块异常:" + str(e)) return ConversationHandler.END
def reset_db(update: Update, _: CallbackContext): input = update.message.text query = update.callback_query if str(input) != str(update.effective_user.id) or str( update.effective_user.id) not in admin_id: user = update.effective_user.name warning("管理员" + user + "在执行数据库重置时输入了错误的ID,执行被取消") text = user + ":\n" + "您输入的ID有误或无管理员权限,数据库的重置已取消" update.message.reply_text(text=text) return ConversationHandler.END if not reset_database(): user = update.effective_user.name error("管理员" + user + "在执行数据库重置时发生了数据库错误,数据库重置失败") text = user + ":\n" + "在执行数据库重置时发生了数据库错误,数据库重置失败" update.message.reply_text(text=text) else: user = update.effective_user.name warning("管理员" + user + "重置了数据库") text = user + ":\n" + "数据库重置成功" update.message.reply_text(text=text) return ConversationHandler.END
def sentence(update: Update, _: CallbackContext) -> None: try: query = update.callback_query query.answer() query.delete_message() type = query.data types = { "a": "动画", "b": "漫画", "c": "游戏", "d": "文学", "e": "原创", "f": "来自网络", "g": "其他", "h": "影视", "i": "诗词", "j": "网易云", "k": "哲学", "l": "抖机灵" } type_name = types[query.data] try: res = requests.get("https://v1.hitokoto.cn?c=" + type) json_res = json.loads(res.text) s = json_res['hitokoto'] author = json_res['from_who'] if author == "null" or author is None: author = "匿名" user = update.effective_user.name + ":\n" text = user + "类型:" + type_name + "\n" + s + "\n作者:" + author info("一言模块:" + text) query.bot.send_message(chat_id=update.effective_chat.id, text=text) except Exception as e: user = update.effective_user.name + ":\n" query.bot.send_message(chat_id=update.effective_chat.id, text=user + "服务器错误,错误原因" + str(e)) except: error("一言模块:发送方法异常") return ConversationHandler.END
def help(update, context): try: user = update.effective_user.name + ":\n" info("帮助模块:" + user + "获取帮助列表") context.bot.send_message( chat_id=update.effective_chat.id, text=user + "/start - 开始\n" "/help - 获得全部指令帮助\n" "/cancel - 终止当前进行中的任务(当机器人不响应的时候请选择)\n" "/stock - 股票信息查询\n" "/stock_mine - 快速查询自选股\n" "/setu - 获取一张随机涩图\n" "/sentence - 一言:获取随机一句名句\n" "/weibo - 获取微博热搜\n" "/zhihu - 随机获取一条知乎日报\n" "/bili - 随机获取一条bilibili热榜视频\n" "/english - 随机获取一条每日英语\n" "/get_me - 获取自己的ID\n" "/admin - 管理员功能" ) except: error("帮助模块异常")
def zhihu(update, context): try: res = requests.get( "https://news-at.zhihu.com/api/3/stories/latest", headers=header) json_str = json.loads(res.text) index = random.randint(0, len(json_str["stories"]) - 1) title = json_str["stories"][index]["title"] url = json_str["stories"][index]["url"] localtime = time.asctime(time.localtime(time.time())) user = update.effective_user.name + ":\n" text = user + '北京时间:' + localtime + " 知乎日报" \ + "\n文章标题:" + title \ + "\n文章链接:" + url info("知乎日报模块:" + text) context.bot.send_message(chat_id=update.effective_chat.id, text=text) except Exception as e: user = update.effective_user.name + ":\n" error("知乎日报模块:服务器获取热搜异常或发送消息异常") context.bot.send_message(chat_id=update.effective_chat.id, text=user + "服务器错误,错误原因:" + str(e))
def english(update, context): try: end_time = datetime.datetime.now() start_time = datetime.datetime.now() + datetime.timedelta( days=-600) a1 = tuple(start_time.timetuple()[0:9]) a2 = tuple(end_time.timetuple()[0:9]) start = time.mktime(a1) end = time.mktime(a2) t = random.randint(int(start), int(end)) date_touple = time.localtime(t) date = time.strftime("%Y-%m-%d", date_touple) res = requests.get( "http://sentence.iciba.com/index.php?c=dailysentence&m=getdetail&title=" + date) json_str = json.loads(res.text) chinese = json_str["note"] english = json_str["content"] pic = json_str["picture2"] voice = json_str["tts"] user = update.effective_user.name + ":\n" text=user + "英文原文:" + english\ + "\n翻译:" + chinese\ + "\n封面:" info("每日英语模块:" + text) context.bot.send_message(chat_id=update.effective_chat.id, text=text) info("每日英语模块:发送图片" + pic) context.bot.send_photo(chat_id=update.effective_chat.id, photo=pic) info("每日英语模块:发送音频" + voice) context.bot.send_voice(chat_id=update.effective_chat.id, voice=voice) except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) error("每日英语模块:" + text) context.bot.send_message(chat_id=update.effective_chat.id, text=text)
def db_management_select(update: Update, _: CallbackContext): try: query = update.callback_query query.answer() query.delete_message() type = query.data if type == "获取数据库信息": user = update.effective_user.name info("一名管理员" + user + "获取了数据库信息") text = user + ":\n" + get_database_message() query.bot.send_message(chat_id=update.effective_chat.id, text=text) return ConversationHandler.END elif type == "重置数据库": user = update.effective_user.name info("一名管理员" + user + "选择了重置数据库,进入验证阶段") text = user + ":\n请输入您的ID来确认重置数据库" query.bot.send_message(chat_id=update.effective_chat.id, text=text) return DELETE_DATABASE except Exception as e: error("数据库管理模块-操作选择接收异常:" + str(e)) return ConversationHandler.END
def admin_select(update: Update, _: CallbackContext) -> int: try: id = update.effective_user.id if str(id) not in admin_id: user = update.effective_user.name warning("管理员模块:一名非管理员用户" + user + "请求访问管理功能") text = user + ":\n" + "您不是管理员,没有本指令权限!\n" \ "如果您是管理员,请先将您的ID添加如配置文件" update.message.reply_text(text) return ConversationHandler.END keyboard = [[InlineKeyboardButton("数据库", callback_data='数据库')], [InlineKeyboardButton("日志", callback_data='日志')]] reply_markup = InlineKeyboardMarkup(keyboard) user = update.effective_user.name text = user + ":\n" + '请选择管理功能' info("管理员模块:一名管理员" + user + "选择了管理员功能") update.message.reply_text( text, reply_markup=reply_markup, ) return ADMIN_SELECT except Exception as e: error("管理员模块异常:" + str(e))
def weibo(update, context): try: res = requests.get("https://s.weibo.com/top/summary") soup = BeautifulSoup(res.text) res = "" for i in range(len(soup.find_all("td", class_="td-02"))): if i == 0: res += ("置顶热搜:" + soup.find_all("td", class_="td-02")[i].a.get_text() + '\n') else: res += ("热搜第" + str(i) + ":" + soup.find_all("td", class_="td-02")[i].a.get_text() + '\n') localtime = time.asctime(time.localtime(time.time())) res += ('北京时间:' + localtime) user = update.effective_user.name+":\n" info("微博热搜模块:"+user+"获取了当前热搜") context.bot.send_message( chat_id=update.effective_chat.id, text=user + res) except Exception as e: user = update.effective_user.name+":\n" error("微博热搜模块:服务器获取热搜异常或发送消息异常") context.bot.send_message( chat_id=update.effective_chat.id, text=user + "服务器错误,错误原因:" + str(e) )
import module.help as help import module.setu as setu import module.sentence as sentence import module.bili as bili import module.weibo as weibo import module.english as english import module.zhihu as zhihu import module.get_me as get_me import module.admin as admin logger_start_check() info("主进程:日志文件检查完成") info("主进程:开始进行数据库检查") # 数据库与Token检查 if not sql_funcs.sql_start_check(): error("主进程:数据库创建或读取错误,请检查") warning("主进程:程序由于异常导致退出") exit(1) info("主进程:数据库检查完成") if config.Token == "": error("主进程:配置文件错误,请先在config.py中输入对应Token后使用") warning("主进程:程序由于异常导致退出") exit(1) if len(config.admin_id) == 0: warning("您未添加管理员,管理员功能将不可用") info("主进程:配置文件检查完成") # 初始化Telegram-Bot
def fast_list_all_mine(update, context): try: stocks = sql_funcs.sql_select_all_mine(update.effective_user.id) if stocks is None: user = update.effective_user.name + ":\n" text = user + "数据库中没有您的自选信息" warning("股票模块-快速打印简报方法:" + text) context.bot.send_message(chat_id=update.effective_chat.id, text=text) else: text = "" for i in stocks: try: session = requests.session() session.get("https://xueqiu.com/k?q=" + i[1], headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + i[1], headers=header) json_str = res.json() # 股票名 name = json_str['data']['items'][0]['quote']['name'] # 数据时间 dt = json_str['data']['items'][0]['quote']['time'] if dt is not None: time_local = time.localtime(dt / 1000) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) # 交易状态 status = json_str['data']['items'][0]['market'][ 'status'] # 现价 current = json_str['data']['items'][0]['quote'][ 'current'] # 昨收 end_price = json_str['data']['items'][0]['quote'][ 'last_close'] # 跌涨数 cost = 0 if current is not None and end_price is not None: cost = current - end_price # 跌涨率% rate = 0 if cost is not None and end_price is not None and cost != 0: rate = cost / end_price cost = float(format(cost, ".2f")) if cost > 0: cost = "+" + str(cost) rate = float(format(rate * 100, ".2f")) if rate > 0: rate = "+" + str(rate) text += "%s" % dt text += "(%s)\n" % status text += "%s " % name text += "(%s)\n" % i[1] text += "现价:%s " % current text += "(%s " % cost text += ",%s%%)\n\n" % rate except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) error("股票模块-快速打印简报方法:" + text) context.bot.send_message( chat_id=update.effective_chat.id, text=text) return info("股票模块-快速打印简报方法:成功获取用户" + update.effective_user.name + "的" + str(len(stocks)) + "条股票数据") user = update.effective_user.name + ":\n" context.bot.send_message(chat_id=update.effective_chat.id, text=user + text) except: error("股票模块-快速打印简报方法异常")
def display_stock(code, update: Update): query = update.callback_query try: session = requests.session() session.get("https://xueqiu.com/k?q=" + code, headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + code, headers=header) json_str = res.json() # 地区 region = json_str['data']['items'][0]['market']['region'] # 交易状态 status = json_str['data']['items'][0]['market']['status'] # 时区 time_zone = json_str['data']['items'][0]['market']['time_zone'] # 交易市场 exchange = json_str['data']['items'][0]['quote']['exchange'] # 货币种类 currency = json_str['data']['items'][0]['quote']['currency'] # 股票名 name = json_str['data']['items'][0]['quote']['name'] # 数据时间 dt = json_str['data']['items'][0]['quote']['time'] if dt is not None: time_local = time.localtime(dt / 1000) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) # 现价 current = json_str['data']['items'][0]['quote']['current'] # 今开 start_price = json_str['data']['items'][0]['quote']['open'] # 昨收 end_price = json_str['data']['items'][0]['quote']['last_close'] # 跌涨数 cost = 0 if current is not None and end_price is not None: cost = current - end_price # 跌涨率% rate = 0 if cost is not None and end_price is not None and cost != 0: rate = cost / end_price cost = float(format(cost, ".2f")) if cost > 0: cost = "+" + str(cost) rate = float(format(rate * 100, ".2f")) if rate > 0: rate = "+" + str(rate) # 最高 high = json_str['data']['items'][0]['quote']['high'] # 最低 low = json_str['data']['items'][0]['quote']['low'] # 成交量(万手) deal = json_str['data']['items'][0]['quote']['volume'] if deal is not None: deal = format(float(format(deal / 10000, ".2f")), ",") # 成交额(万元) amount = json_str['data']['items'][0]['quote']['amount'] if amount is not None: amount = format(int(format(amount / 10000, ".0f")), ",") # 换手 turnover_rate = json_str['data']['items'][0]['quote'][ 'turnover_rate'] # 振幅 amplitude = json_str['data']['items'][0]['quote']['amplitude'] # 市值(万元) total_price = json_str['data']['items'][0]['quote'][ 'market_capital'] if total_price is not None: total_price = format(int(format(total_price / 10000, ".0f")), ",") # 总股本(万元) total_shares = json_str['data']['items'][0]['quote'][ 'total_shares'] if total_price is not None: total_shares = format(int(format(total_shares / 10000, ".0f")), ",") text = "股票名称:%s\n" % name text += "股票代码:%s\n" % code text += "地区:%s\n" % region text += "时区:%s\n" % time_zone text += "交易市场:%s\n" % exchange text += "货币种类:%s\n" % currency text += "交易状态:%s\n" % status text += "数据时间(当地):%s\n" % dt text += "现价:%s\n" % current text += "今开:%s\n" % start_price text += "昨收:%s\n" % end_price text += "跌涨:%s\n" % cost text += "跌涨率:%s%%\n" % rate text += "最高:%s\n" % high text += "最低:%s\n" % low text += "成交量:%s万手\n" % deal text += "成交额:%s万\n" % amount text += "换手:%s%%\n" % turnover_rate text += "振幅:%s%%\n" % amplitude text += "市值:%s万\n" % total_price text += "总股本:%s万" % total_shares user = update.effective_user.name + ":\n" info("股票模块-自选股-自选股具体信息:用户" + update.effective_user.name + "打印了一条股票具体信息,股票代码:" + code) query.bot.send_message(chat_id=update.effective_chat.id, text=user + text) except Exception as e: user = update.effective_user.name + ":\n" text = user + "服务器错误,错误原因:" + str(e) error("股票模块-自选股-自选股具体信息:" + text) query.bot.send_message(chat_id=update.effective_chat.id, text=text)
def stock_mine(update: Update, _: CallbackContext) -> int: try: query = update.callback_query query.answer() query.delete_message() if query.data == "添加自选": user = update.effective_user.name + ":\n" info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择添加一条自选") query.bot.send_message(chat_id=update.effective_chat.id, text=user + "请输入搜索词") return STOCK_ADD_MINE elif query.data == "删除自选": info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择删除一条自选") if not stock_list_mine(update): return ConversationHandler.END else: return STOCK_DELETE_MINE elif query.data == "查看自选": info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择查看全部自选") if not stock_list_mine(update): return ConversationHandler.END else: return STOCK_SELECT elif query.data == "列出全部自选": info("股票模块-自选股功能-自选股功能选择处理器:用户" + update.effective_user.name + "选择列出全部自选简报") stocks = sql_funcs.sql_select_all_mine( update.effective_user.id) if stocks is None: user = update.effective_user.name + ":\n" query.bot.send_message(chat_id=update.effective_chat.id, text=user + "数据库中没有您的自选信息") else: stocks = sql_funcs.sql_select_all_mine( update.effective_user.id) if stocks is None: user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "数据库中没有您的自选信息") else: text = "" for i in stocks: try: session = requests.session() session.get("https://xueqiu.com/k?q=" + i[1], headers=header) res = session.get( "https://stock.xueqiu.com/v5/stock/batch/quote.json?symbol=" + i[1], headers=header) json_str = res.json() # 股票名 name = json_str['data']['items'][0]['quote'][ 'name'] # 数据时间 dt = json_str['data']['items'][0]['quote'][ 'time'] if dt is not None: time_local = time.localtime(dt / 1000) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) # 交易状态 status = json_str['data']['items'][0][ 'market']['status'] # 现价 current = json_str['data']['items'][0][ 'quote']['current'] # 昨收 end_price = json_str['data']['items'][0][ 'quote']['last_close'] # 跌涨数 cost = 0 if current is not None and end_price is not None: cost = current - end_price # 跌涨率% rate = 0 if cost is not None and end_price is not None and cost != 0: rate = cost / end_price cost = float(format(cost, ".2f")) if cost > 0: cost = "+" + str(cost) rate = float(format(rate * 100, ".2f")) if rate > 0: rate = "+" + str(rate) text += "%s" % dt text += "(%s)\n" % status text += "%s " % name text += "(%s)\n" % i[1] text += "现价:%s " % current text += "(%s " % cost text += ",%s%%)\n\n" % rate except Exception as e: user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + "服务器错误,错误原因:" + str(e)) return ConversationHandler.END user = update.effective_user.name + ":\n" query.bot.send_message( chat_id=update.effective_chat.id, text=user + text) return ConversationHandler.END except: error("股票模块-自选股功能-自选股功能选择处理器异常") return ConversationHandler.END