Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/modules/meme/urban.py

47 lines
1.7 KiB
Python
Raw Normal View History

2022-01-08 14:58:08 +00:00
import traceback
2022-01-20 12:13:03 +00:00
2022-01-03 09:13:42 +00:00
import ujson as json
2022-01-08 14:03:09 +00:00
from config import Config
2022-01-17 13:28:49 +00:00
from core.elements import Url
2022-01-03 09:13:42 +00:00
from core.utils import get_url
2022-01-20 12:13:03 +00:00
2022-01-03 09:13:42 +00:00
async def urban(term: str):
'''查询urban dictionary。
:param term: 需要查询的term
:returns: 查询结果'''
try:
url = 'http://api.urbandictionary.com/v0/define?term=' + term
2022-01-08 14:03:09 +00:00
webrender = Config('web_render')
2022-06-15 00:29:20 +00:00
if not webrender:
return
url = webrender + 'source?url=' + url
2022-08-01 15:33:35 +00:00
text = await get_url(url, 200, headers={'accept': '*/*',
'accept-encoding': 'gzip, deflate',
'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,en-GB;q=0.6',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62'})
2022-01-08 14:03:09 +00:00
print(text)
2022-01-03 09:13:42 +00:00
data = json.loads(text)['list']
if data == []:
return '[Urban Dictionary] 没有找到相关结果。'
else:
count = data.__len__()
word = data[0]['word']
2022-01-08 14:47:24 +00:00
definition = limit_length(data[0]['definition'])
example = limit_length(data[0]['example'])
2022-01-03 09:13:42 +00:00
link = data[0]['permalink']
2022-01-17 13:28:49 +00:00
return f'[Urban Dictionary]{count}个结果):\n{word}\n{definition}\nExample: {example}\n{str(Url(link))}'
2022-01-08 14:58:08 +00:00
except Exception:
traceback.print_exc()
2022-01-03 09:13:42 +00:00
return '[Urban Dictionary] 查询出错。'
2022-01-08 14:47:24 +00:00
def limit_length(text, limit=50):
2022-01-08 14:58:08 +00:00
new = text
length = new.split(' ').__len__()
2022-01-08 14:47:24 +00:00
if length > limit:
2022-01-08 14:58:08 +00:00
new = ' '.join(new.split(' ')[0:limit]) + ''
return new