支持地理位置解析

This commit is contained in:
xtaodada 2022-10-13 22:36:43 +08:00
parent a3ffb71d03
commit 9ec05abb52
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
5 changed files with 74 additions and 15 deletions

View File

@ -23,3 +23,6 @@ access_token_secret = ABCD
admin = 0 admin = 0
lofter_channel = 0 lofter_channel = 0
lofter_channel_username = username lofter_channel_username = username
[api]
amap_key = ABCD

View File

@ -16,6 +16,8 @@ access_token_secret: str = ""
admin: int = 0 admin: int = 0
lofter_channel: int = 0 lofter_channel: int = 0
lofter_channel_username: str = "" lofter_channel_username: str = ""
# [api]
amap_key: str = ""
config = RawConfigParser() config = RawConfigParser()
config.read("config.ini") config.read("config.ini")
@ -29,6 +31,7 @@ access_token_secret = config.get("twitter", "access_token_secret", fallback=acce
admin = config.getint("post", "admin", fallback=admin) admin = config.getint("post", "admin", fallback=admin)
lofter_channel = config.getint("post", "lofter_channel", fallback=lofter_channel) lofter_channel = config.getint("post", "lofter_channel", fallback=lofter_channel)
lofter_channel_username = config.get("post", "lofter_channel_username", fallback=lofter_channel_username) lofter_channel_username = config.get("post", "lofter_channel_username", fallback=lofter_channel_username)
amap_key = config.get("api", "amap_key", fallback=amap_key)
try: try:
ipv6 = strtobool(ipv6) ipv6 = strtobool(ipv6)
except ValueError: except ValueError:

43
modules/geo.py Normal file
View File

@ -0,0 +1,43 @@
import contextlib
from urllib.parse import quote
from pyrogram import Client, filters
from pyrogram.types import Message
from defs.glover import amap_key
from init import user_me, request
REQUEST_URL = f"https://restapi.amap.com/v3/geocode/geo?key={amap_key}&"
@Client.on_message(filters.incoming &
filters.command(["geo", f"geo@{user_me.username}"]))
async def geo_command(_: Client, message: Message):
if len(message.command) <= 1:
await message.reply('没有找到要查询的中国 经纬度/地址 ...')
return
mode, lat, lon = "address", 0, 0 # noqa
with contextlib.suppress(ValueError, IndexError):
lat, lon = float(message.command[1]), float(message.command[2])
mode = "location"
if mode == "location":
try:
geo = (await request.get(f"{REQUEST_URL.replace('/geo?', '/regeo?')}location={lat},{lon}")).json()
formatted_address = geo["regeocode"]["formatted_address"]
assert isinstance(formatted_address, str)
except (KeyError, AssertionError):
await message.reply(f"无法解析经纬度 {lat}, {lon}", quote=True)
return
else:
try:
geo = (await request.get(f"{REQUEST_URL}address={quote(' '.join(message.command[1:]).strip())}")).json()
formatted_address = geo["geocodes"][0]["formatted_address"]
lat, lon = geo["geocodes"][0]["location"].split(",")
except (KeyError, IndexError, ValueError):
await message.reply(f"无法解析地址 {' '.join(message.command[1:]).strip()}", quote=True)
return
msg = await message.reply_location(longitude=float(lat), latitude=float(lon), quote=True)
await msg.reply(f"坐标:`{lat},{lon}`\n"
f"地址:<b>{formatted_address}</b>", quote=True)

View File

@ -28,9 +28,7 @@ async def lofter_share(_: Client, message: Message):
await img[0].reply_to(message, static=static) await img[0].reply_to(message, static=static)
else: else:
await message.reply_media_group(media=await input_media(img[:9], static), quote=True) await message.reply_media_group(media=await input_media(img[:9], static), quote=True)
elif "front/blog" in url: elif "front/blog" not in url:
pass
else:
text, avatar, username, status_link = await get_loft_user(url) text, avatar, username, status_link = await get_loft_user(url)
if avatar: if avatar:
await message.reply_photo( await message.reply_photo(

View File

@ -29,13 +29,19 @@ async def twitter_share(client: Client, message: Message):
if url.hostname and url.hostname in ["twitter.com", "vxtwitter.com"]: if url.hostname and url.hostname in ["twitter.com", "vxtwitter.com"]:
if url.path.find('status') >= 0: if url.path.find('status') >= 0:
status_id = str(url.path[url.path.find('status') + 7:].split("/")[0]).split("?")[0] status_id = str(url.path[url.path.find('status') + 7:].split("/")[0]).split("?")[0]
url_json = None
with ThreadPoolExecutor() as executor: with ThreadPoolExecutor() as executor:
for _ in range(3):
try: try:
future = client.loop.run_in_executor(executor, twitter_api.GetStatus, status_id) future = client.loop.run_in_executor(executor, twitter_api.GetStatus, status_id)
url_json = await asyncio.wait_for(future, timeout=30, loop=client.loop) url_json = await asyncio.wait_for(future, timeout=30, loop=client.loop)
except Exception as e: except Exception as e:
print(e) print(e)
return return
if url_json:
break
if not url_json:
return
text, user_text, media_model, media_list, quoted_status = get_twitter_status(url_json) text, user_text, media_model, media_list, quoted_status = get_twitter_status(url_json)
text = f'<b>Twitter Status Info</b>\n\n{text}\n\n{user_text}' text = f'<b>Twitter Status Info</b>\n\n{text}\n\n{user_text}'
if len(media_model) == 0: if len(media_model) == 0:
@ -87,13 +93,19 @@ async def twitter_share(client: Client, message: Message):
else: else:
# 解析用户 # 解析用户
uid = url.path.replace('/', '') uid = url.path.replace('/', '')
url_json = None
with ThreadPoolExecutor() as executor: with ThreadPoolExecutor() as executor:
for _ in range(3):
try: try:
future = client.loop.run_in_executor(executor, twitter_api.GetUser, None, uid) future = client.loop.run_in_executor(executor, twitter_api.GetUser, None, uid)
url_json = await asyncio.wait_for(future, timeout=30, loop=client.loop) url_json = await asyncio.wait_for(future, timeout=30, loop=client.loop)
except Exception as e: except Exception as e:
print(e) print(e)
return return
if url_json:
break
if not url_json:
return
text, user_username, status_link = get_twitter_user(url_json) text, user_username, status_link = get_twitter_user(url_json)
await message.reply_photo( await message.reply_photo(
url_json.profile_image_url_https.replace('_normal', ''), url_json.profile_image_url_https.replace('_normal', ''),