Skip to content

Commit

Permalink
Merging the branch (MadeByThePinsHub#39)
Browse files Browse the repository at this point in the history
* cleanup

* Lydia in PM now uwu

Fixed issues with Lydia not working in Private Messages

* Adding Updater for non Heroku Users to Assistant
  • Loading branch information
CustomIcon authored Sep 28, 2020
1 parent e1aa0b4 commit fd076bb
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 89 deletions.
119 changes: 71 additions & 48 deletions nana/assistant/inline.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import traceback
import random
import requests
import aiohttp
import git
import os
from datetime import datetime
Expand Down Expand Up @@ -305,53 +305,76 @@ async def inline_query_handler(client, query):
return
search = string.split(None, 1)[1]
variables = {'search' : search}
json = requests.post(url, json={'query': anime_query, 'variables': variables}).json()['data'].get('Media', None)
if json:
msg = f"**{json['title']['romaji']}** (`{json['title']['native']}`)\n**Type**: {json['format']}\n**Status**: {json['status']}\n**Episodes**: {json.get('episodes', 'N/A')}\n**Duration**: {json.get('duration', 'N/A')} Per Ep.\n**Score**: {json['averageScore']}\n**Genres**: `"
for x in json['genres']:
msg += f"{x}, "
msg = msg[:-2] + '`\n'
msg += "**Studios**: `"
for x in json['studios']['nodes']:
msg += f"{x['name']}, "
msg = msg[:-2] + '`\n'
info = json.get('siteUrl')
trailer = json.get('trailer', None)
if trailer:
trailer_id = trailer.get('id', None)
site = trailer.get('site', None)
if site == "youtube": trailer = 'https://youtu.be/' + trailer_id
description = json.get('description', 'N/A').replace('<i>', '').replace('</i>', '').replace('<br>', '')
msg += shorten(description, info)
image = json.get('bannerImage', None)
if trailer:
buttons = [[InlineKeyboardButton("More Info", url=info), InlineKeyboardButton("Trailer 🎬", url=trailer)],
[InlineKeyboardButton('Add to Watchlist', callback_data=f'addfav_{json["title"]["romaji"]}')]]
else:
buttons = [[InlineKeyboardButton("More Info", url=info),
InlineKeyboardButton('Add to Watchlist', callback_data=f'addfav_{json["title"]["romaji"]}')]]
if image:
answers.append(InlineQueryResultPhoto(
caption=msg,
photo_url=image,
parse_mode="markdown",
title=f"{json['title']['romaji']}",
description=f"{json['format']}",
reply_markup=InlineKeyboardMarkup(buttons)))
await client.answer_inline_query(query.id,
results=answers,
cache_time=0
)
else:
answers.append(InlineQueryResultArticle(
title=f"{json['title']['romaji']}",
description=f"{json['averageScore']}",
input_message_content=InputTextMessageContent(msg, parse_mode="markdown", disable_web_page_preview=True),
reply_markup=InlineKeyboardMarkup(buttons)))
await client.answer_inline_query(query.id,
results=answers,
cache_time=0
)
async with aiohttp.ClientSession() as session:
async with session.post(url, json={'query': anime_query, 'variables': variables}) as resp:
r = await resp.json()
json = r['data'].get('Media', None)
if json:
msg = f"**{json['title']['romaji']}** (`{json['title']['native']}`)\n**Type**: {json['format']}\n**Status**: {json['status']}\n**Episodes**: {json.get('episodes', 'N/A')}\n**Duration**: {json.get('duration', 'N/A')} Per Ep.\n**Score**: {json['averageScore']}\n**Genres**: `"
for x in json['genres']:
msg += f"{x}, "
msg = msg[:-2] + '`\n'
msg += "**Studios**: `"
for x in json['studios']['nodes']:
msg += f"{x['name']}, "
msg = msg[:-2] + '`\n'
info = json.get('siteUrl')
trailer = json.get('trailer', None)
if trailer:
trailer_id = trailer.get('id', None)
site = trailer.get('site', None)
if site == "youtube": trailer = 'https://youtu.be/' + trailer_id
description = json.get('description', 'N/A').replace('<i>', '').replace('</i>', '').replace('<br>', '')
msg += shorten(description, info)
image = json.get('bannerImage', None)
if trailer:
buttons = [[InlineKeyboardButton("More Info", url=info), InlineKeyboardButton("Trailer 🎬", url=trailer)],
[InlineKeyboardButton('Add to Watchlist', callback_data=f'addfav_{json["title"]["romaji"]}')]]
else:
buttons = [[InlineKeyboardButton("More Info", url=info),
InlineKeyboardButton('Add to Watchlist', callback_data=f'addfav_{json["title"]["romaji"]}')]]
if image:
answers.append(InlineQueryResultPhoto(
caption=msg,
photo_url=image,
parse_mode="markdown",
title=f"{json['title']['romaji']}",
description=f"{json['format']}",
reply_markup=InlineKeyboardMarkup(buttons)))
else:
answers.append(InlineQueryResultArticle(
title=f"{json['title']['romaji']}",
description=f"{json['averageScore']}",
input_message_content=InputTextMessageContent(msg, parse_mode="markdown", disable_web_page_preview=True),
reply_markup=InlineKeyboardMarkup(buttons)))
await client.answer_inline_query(query.id,
results=answers,
cache_time=0
)

elif string.split()[0] == "favourite":
fav = sql.get_fav(Owner)
if fav:
text = "**My watchlist:**\n"
for title in fav:
text += f" - {title.data}\n"
keyb = [
[InlineKeyboardButton(text="Watched ✅", callback_data=f"remfav_{Owner}")]
]
answers.append(InlineQueryResultArticle(
title="Favourites",
description="Anime",
input_message_content=InputTextMessageContent(text, parse_mode="markdown"),
reply_markup=InlineKeyboardMarkup(keyb)))
else:
answers.append(InlineQueryResultArticle(
title="Fabourites",
description="Anime",
input_message_content=InputTextMessageContent("**No favourites yet!**", parse_mode="markdown")))
await client.answer_inline_query(query.id,
results=answers,
cache_time=0
)

elif string.split()[0] == "favourite":
fav = sql.get_fav(Owner)
Expand Down
12 changes: 11 additions & 1 deletion nana/assistant/updater.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import random

import os
from git import Repo
from git.exc import GitCommandError, NoSuchPathError, InvalidGitRepositoryError
from pyrogram import filters
Expand Down Expand Up @@ -134,6 +134,16 @@ async def update_button(client, query):
await client.send_message(Owner, "no heroku application found, but a key given? 😕 ")
await client.send_message(Owner, "Build Unsuccess, Check heroku build log for more detail")
return
else:
try:
os.system('git reset --hard')
os.system('git pull')
os.system('pip install -U -r requirements.txt')
await client.send_message(Owner, "Built Successfully, Please Restart Manually in /settings")
return
except Exception as e:
await client.send_message(Owner, f"Build Unsuccess,\nLog:{e}")
return
try:
upstream.pull(brname)
await client.send_message(Owner, "Successfully Updated!\nBot is restarting...")
Expand Down
22 changes: 6 additions & 16 deletions nana/helpers/deldog.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
import requests

import aiohttp

async def deldog(message, data):
BASE_URL = 'https://del.dog'
r = requests.post(f'{BASE_URL}/documents', data=data.encode('utf-8'))
if r.status_code == 404:
await message.edit('Failed to reach dogbin')
r.raise_for_status()
res = r.json()
if r.status_code != 200:
await message.edit(res['message'])
r.raise_for_status()
key = res['key']
if res['isUrl']:
reply = f'Shortened URL: {BASE_URL}/{key}\nYou can view stats, etc. [here]({BASE_URL}/v/{key})'
else:
reply = f'{BASE_URL}/{key}'
BASE_URL = 'https://nekobin.com'
async with aiohttp.ClientSession() as session:
async with session.post(f'{BASE_URL}/api/documents', json={"content":data}, timeout=3) as response:
key = (await response.json())["result"]["key"]
reply = f'{BASE_URL}/raw/{key}'
return reply
29 changes: 14 additions & 15 deletions nana/modules/animelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,20 +74,20 @@ def t(milliseconds: int) -> str:

airing_query = '''
query ($id: Int,$search: String) {
Media (id: $id, type: ANIME,search: $search) {
id
episodes
title {
romaji
english
native
Media (id: $id, type: ANIME,search: $search) {
id
episodes
title {
romaji
english
native
}
nextAiringEpisode {
airingAt
timeUntilAiring
episode
}
}
nextAiringEpisode {
airingAt
timeUntilAiring
episode
}
}
}
'''

Expand Down Expand Up @@ -233,8 +233,7 @@ async def character_search(client, message):
return
search = search[1]
variables = {'query': search}
json = requests.post(url, json={'query': character_query, 'variables': variables}).json()[
'data'].get('Character', None)
json = requests.post(url, json={'query': character_query, 'variables': variables}).json()['data'].get('Character', None)
if json:
ms_g = f"**{json.get('name').get('full')}**(`{json.get('name').get('native')}`)\n"
description = f"{json['description']}"
Expand Down
14 changes: 8 additions & 6 deletions nana/modules/lydia.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,13 @@ async def chat_bot(client, message):


async def check_message(_client, message):
reply_msg = message.reply_to_message
if message.text.lower() == f"@{OwnerUsername}":
if message.chat.type == 'private':
return True
if reply_msg:
if reply_msg.from_user.id == Owner:
return True
else:
return False
if message.text.lower() == f"@{OwnerUsername}":
return True
if message.reply_to_message:
if message.reply_to_message.from_user.id == Owner:
return True
else:
return False
4 changes: 2 additions & 2 deletions nana/modules/ocr.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ async def ocr(client, message):
try:
ParsedText = test_file["ParsedResults"][0]["ParsedText"]
except BaseException as e:
await message.reply(e)
await edrep(message, text=e)
else:
if ParsedText == 'ParsedResults':
await message.delete()
return
else:
await message.reply(f"`{ParsedText}`")
await edrep(message, text=f"`{ParsedText}`")
os.remove(downloaded_file_name)
2 changes: 1 addition & 1 deletion nana/modules/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ async def updater(client, message):
file.write(changelog_str)
file.close()
await client.send_document(message.chat.id, "nana/cache/output.txt", reply_to_message_id=message.message_id,
caption="`Changelog file`")
caption="`Changelog file`")
os.remove("nana/cache/output.txt")
else:
await edrep(message, text=changelog_str)
Expand Down

0 comments on commit fd076bb

Please sign in to comment.