compared with github

This commit is contained in:
Andrew Linim 2024-11-05 23:37:37 +03:00
parent 24fb75e441
commit c99f8e3716
3 changed files with 105 additions and 20 deletions

View file

@ -2,10 +2,9 @@
## Google-Images-Search wrapper bot for Next ## Google-Images-Search wrapper bot for Next
### Installation: ### Installation:
1. Download [Next.py library](https://autumn.avanpost20.ru/attachments/download/WL1PuZrNahl8rSzi7xItxrbd5GHwn47kdQyHG6f1rF) and install downloaded file with `pip install ./next.py-0.2.0-py3-none-any.whl` 1. Install next-api-py library via Pip: `pip install next-api-py`
2. Install Google-Images-Search library via Pip: pip install `google-images-search` 2. Install Google-Images-Search library via Pip: `pip install google-images-search`
3. If you using a Windows, install a windows-curses library via Pip: `pip install windows-curses` 3. If you using a Windows, install a windows-curses library via Pip: `pip install windows-curses`
4. Clone repository to local drive using `git clone https://github.com/hlnmplus/GImages/` 4. Clone repository to local drive using `git clone https://github.com/hlnmplus/GImages/`
5. Set up your Next and Google credentials in creds.py file 5. Set up your Next and Google credentials in `creds.py` file
6. All done! Now, you can run your own instance of bot by running main.py 6. All done! Now, you can run your own instance of bot by running `main.py`

71
log.py Normal file
View file

@ -0,0 +1,71 @@
from time import gmtime, strftime
loggers = {}
def getCurrentTime():
"""Get current time"""
return strftime("%H:%M:%S", gmtime())
def createLogger(loggerName = 'main', fileName = 'latest.log', branding = None, printLogs = False):
"""Create a logger"""
if loggerName in loggers.keys():
raise Exception(f'Logger named "{loggerName}" already exist')
logging = open(fileName, 'w')
logging.truncate(0)
logging.close()
class logger:
log_file = fileName
log_brand = branding
log_print = printLogs
logTemplate = "[{}]{}{}"
def log(text):
log_brand = branding
logging = open(logger.log_file, 'a')
if log_brand == None:
logRender = logger.logTemplate.format(getCurrentTime(), ' ', text)
else:
logRender = logger.logTemplate.format(getCurrentTime(), f'[{logger.log_brand}]', text)
if logger.log_print == True:
print(logRender)
logging.write(f'{logRender}\n')
return True
def warn(text):
logger.log("".join(['[WARN] ', text]))
def info(text):
logger.log("".join(['[INFO] ', text]))
def error(text):
logger.log("".join(['[ERROR] ', text]))
def close():
del logger.log, logger.warn, logger.info, logger.error, logger.log_file, logger.log_brand, logger.log_print
loggers[loggerName] = logger
logger.log('GImages started')
return logger
def getLogger(loggerName):
"""Get created logger"""
return loggers[loggerName]
def delLogger(loggerName):
"""Delete created logger"""
loggers[loggerName].close()
del loggers[loggerName]

39
main.py
View file

@ -1,11 +1,19 @@
import asyncio import asyncio
import aiohttp import aiohttp
import next import next
import log
import creds import creds
from time import sleep
from random import choice
from creds import gimgsettings from creds import gimgsettings
from next.ext import commands from next.ext import commands
from api import get_img from api import get_img
version = "1.0.4"
logger = log.createLogger(fileName = "gimg.log")
logger.log('Starting GImages')
class Client(commands.CommandsClient): class Client(commands.CommandsClient):
async def get_prefix(self, message: next.Message): async def get_prefix(self, message: next.Message):
return "!" return "!"
@ -14,35 +22,37 @@ class Client(commands.CommandsClient):
async def gimg(self, ctx: commands.Context, *args): async def gimg(self, ctx: commands.Context, *args):
"""[count of images, 1 by default] - get image from Google Images""" """[count of images, 1 by default] - get image from Google Images"""
arg = "" query = ""
banned = False banned = False
if gimgsettings['usestoplist'] == True:
for banword in gimgsettings['stoplist']:
if banword in arg:
banned = True
else:
pass
try: try:
count = int(args[0]) count = int(args[0])
for word in range(1, len(args)): for word in range(1, len(args)):
arg += f"{args[word]} " query += f"{args[word]} "
except: except:
count = 1 count = 1
for word in args: for word in args:
arg += f"{word} " query += f"{word} "
if gimgsettings['usestoplist'] == True:
for banword in gimgsettings['stoplist']:
if banword in query:
banned = True
else:
pass
if count > 10: if count > 10:
toomanyimages = True toomanyimages = True
else: else:
toomanyimages = False toomanyimages = False
logger.log(f'{ctx.author.id} ({ctx.author.original_name}#{ctx.author.discriminator}) requested count={count}, query="{query}"')
if toomanyimages == False and banned == False: if toomanyimages == False and banned == False:
try: try:
url = get_img(arg, count) # requesting image url = get_img(query, count) # requesting image
await ctx.send(f"Search query: {arg}\n{url}") # sending image via embed await ctx.send(f"Search query: {query}\n{url}") # sending image via embed
except IndexError: except IndexError:
await ctx.send("No images found") await ctx.send("No images found")
elif banned == True: elif banned == True:
@ -55,6 +65,11 @@ async def main():
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
client = Client(session, creds.bot) client = Client(session, creds.bot)
print("Running GImages") print("Running GImages")
logger.info(f"GImages started, v{version}")
await client.start() await client.start()
asyncio.run(main())
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info(f"GImages exited manually")