Ejemplo n.º 1
0
Archivo: api.py Proyecto: Narfee/neo
 async def image_callback(self, ctx, **flags):
     """
     Search Google Images for the query
     """
     safesearch = True
     if isinstance(ctx.channel, discord.DMChannel) or ctx.channel.nsfw:
         safesearch = flags["safesearch"]
     embeds = []
     async with ctx.loading(tick=False):
         keys = neo.secrets.gimage_keys
         cli = cse.Search(keys, session=self.bot.session)
         res = await cli.search(
             " ".join(flags["query"]), image_search=True, safesearch=safesearch
         )
         embeds = build_google_embeds(res)
     if not embeds:
         return
     source = PagedEmbedMenu(embeds)
     menu = CSMenu(
         source,
         delete_on_button=True,
         footer_extra=f"Safesearch: {safesearch}",
         clear_reactions_after=True,
         has_permissions={"administrator": True},
     )
     await menu.start(ctx)
Ejemplo n.º 2
0
    def __init__(self, bot):
        self.bot = bot
        self.d = self.bot.d

        self.google_client = async_cse.Search(self.d.google_keys)

        self.db = self.bot.get_cog('Database')
Ejemplo n.º 3
0
 def __init__(self, bot):
     self.bot = bot
     self.icon = "🌐"
     self.twitter_api = tweepy.API(
         OAuthHandler(TWITTER_CKEY, TWITTER_CSECRET))
     self.google_client = async_cse.Search(GCS_DEVELOPER_KEY)
     self.ig_colors = [
         int("405de6", 16),
         int("5851db", 16),
         int("833ab4", 16),
         int("c13584", 16),
         int("e1306c", 16),
         int("fd1d1d", 16),
         int("f56040", 16),
         int("f77737", 16),
         int("fcaf45", 16),
     ]
     self.regions = {
         "kr": "www",
         "korea": "www",
         "eune": "eune",
         "euw": "euw",
         "jp": "jp",
         "japan": "jp",
         "na": "na",
         "oceania": "oce",
         "oce": "oce",
         "brazil": "br",
         "las": "las",
         "russia": "ru",
         "ru": "ru",
         "turkey": "tr",
         "tr": "tr",
     }
     self.user_agents = UserAgent()
Ejemplo n.º 4
0
async def search(ctx, *, args):
    isbad2 = better_profanity.profanity.contains_profanity(args)

    if ((isbad2 == True) or (args in badsearch)):
            badresponse = random.choice(["This is why your parents don't love you","Really?","You are just an asshole. You know that?","God has abandoned us","Horny bastard"])
            await ctx.send(badresponse)
            print(f"\u001b[33;1m{ctx.message.author} tried to search '{args}'\u001b[31m")


    elif (args.find("urbandictionary") == True):
        await ctx.send("Lol no")

    elif "://" in args:
        await ctx.send("You think I'm stupid? Don't answer that.")

    if ctx.message.author.id in bannedids:
        noresponses = random.choice(["Did you really think that would work?","I'm not stupid, you are banned","Begone","Nope","All aboard the nope train to nahland","Twat","How about no"])
        await ctx.send(noresponses) #a user banned from the search command cos they tried to search "male docking" 82 times

    else :
            client = async_cse.Search("AIzaSyAIc3NVCXoMDUzvY4sTr7hPyRQREdPUVg4") # create the Search client (uses Google by default!)
            results = await client.search(args, safesearch=True) # returns a list of async_cse.Result objects
            first_result = results[0] # Grab the first result
            if "urbandictionary" in first_result.url:
                await ctx.send("Thanks to <@567522840752947210>, urban dictionary is banned")
            else:
                await ctx.send(f"**{first_result.title}**\n{first_result.url}")
                await client.close()
                f = open(f"{filepath}/logs.txt", "a")
                f.write(f"{datetime.datetime.now()} - {ctx.message.guild.name} | {ctx.message.author} : !search {args} -> {first_result.url}\n")
                f.close()
Ejemplo n.º 5
0
 def __init__(self, bot):
     self.bot = bot
     self.google = async_cse.Search(
         GOOGLE_CSE_KEY,
         session=bot.session
     )
     self.fail_msg = ("Une erreur s'est produite, veuiller réesayer.\n"
                      "*Si ce message persiste, alors veillez réessayer plus tard.*")
Ejemplo n.º 6
0
    def __init__(self, bot):
        self.bot = bot

        self.d = bot.d

        self.google_client = async_cse.Search(bot.k.google)

        self.db = bot.get_cog("Database")
Ejemplo n.º 7
0
 def __init__(self, bot):
     self.bot = bot
     self.google_client = async_cse.Search(GCS_DEVELOPER_KEY)
     self.icon = "💃"
     self.gender_icon = {
         "F": ":female_sign: ",
         "M": ":male_sign: ",
     }
Ejemplo n.º 8
0
    def __init__(self, bot):
        self.bot = bot

        self.g = self.bot.get_cog("Global")
        self.db = self.bot.get_cog("Database")

        with open("data/keys.json", "r") as keys:
            self.google = async_cse.Search(json.load(keys)["googl"])
Ejemplo n.º 9
0
    def __init__(self, bot):
        self.bot = bot

        self.g = self.bot.get_cog("Global")

        self.tips = ["Made by Iapetus11#6821 & TrustedMercury#1953", "You can get emeralds by voting for the bot on top.gg!",
                     "Hey, check out the support server! discord.gg/39DwwUV", "Did you know you can buy emeralds?",
                     f"Wanna invite the bot? Try the !!invite command!", "Did you know you can get emeralds by voting for the bot?"]

        with open("data/keys.json", "r") as keys:
            self.google = async_cse.Search(json.load(keys)["googl"])
Ejemplo n.º 10
0
 async def google(self, ctx, *, query=None):
     """Shows you google search results for a specified query"""
     client = async_cse.Search(self.bot.config.google_key)
     results = await client.search(query, safesearch=not (ctx.channel.is_nsfw()))
     embeds = []
     for res in results:
         embeds.append(
             discord.Embed(colour=self.bot.colour, title=res.title, description=res.description, url=res.url))
     source = paginator.EmbedSource(embeds)
     await client.close()
     await paginator.CatchAllMenu(source=source).start(ctx)
Ejemplo n.º 11
0
    def __init__(self, bot):
        self.bot = bot

        self.d = bot.d
        self.db = bot.get_cog("Database")
        self.ipc = bot.ipc

        self.google = async_cse.Search(bot.k.google_search)

        self.ban_count_cache = {}

        self.snipes = {}
        self.clear_snipes.start()
Ejemplo n.º 12
0
async def search(ctx, *, val=None):
    if settings.check(ctx.message.guild.id, "get", "search"):
        if val == None:
            await ctx.send("You need to give me a query")
        else:
            isbad2 = better_profanity.profanity.contains_profanity(val)
            if money.ranktoid(ctx.message.author.id) >= 3:

                if ((isbad2) or (val in badsearch)):
                    badresponse = random.choice([
                        "This is why your parents don't love you", "Really?",
                        "You are just an asshole. You know that?",
                        "God has abandoned us", "Horny bastard"
                    ])
                    await ctx.send(badresponse)
                    print(
                        f"\u001b[33;1m{ctx.message.author} tried to search '{val}'\u001b[31m"
                    )

                elif (val.find("urbandictionary")):
                    await ctx.send("Lol no")

                elif "://" in val:
                    await ctx.send("You think I'm stupid? Don't answer that.")

                if botlib.check_banned(ctx):
                    # create the Search client (uses Google by default-)
                    client = async_cse.Search(
                        "AIzaSyAIc3NVCXoMDUzvY4sTr7hPyRQREdPUVg4")
                    # returns a list of async_cse.Result objects
                    results = await client.search(val, safesearch=True)
                    first_result = results[0]  # Grab the first result
                    if "urbandictionary" in first_result.url:
                        await ctx.send(
                            "Thanks to <@567522840752947210>, urban dictionary is banned"
                        )
                    else:
                        await ctx.send(
                            f"**{first_result.title}**\n{first_result.url}")
                        await client.close()
                        f = open(f"{filepath}/logs.txt", "a")
                        f.write(
                            f"{datetime.datetime.now()} - {ctx.message.guild.name} | {ctx.message.author} : !search {val} -> {first_result.url}\n"
                        )
                        f.close()
                else:
                    await ctx.send(botlib.nope)
            else:
                await ctx.send("You don't have a high enough rank for this")
    else:
        await ctx.send("Sorry, searches are disabled for this server")
Ejemplo n.º 13
0
 async def image(self, ctx, *, query=None):
     """Shows you google image results for a specified query"""
     client = async_cse.Search(secrets()['google_key'])
     results = await client.search(query, safesearch=ctx.channel.is_nsfw())
     embeds = []
     for res in results:
         if not res.image_url:
             continue
         else:
             print(res.image_url)
             embeds.append(discord.Embed(colour=self.client.colour, title=res.title, description=res.description,
                                         url=res.url).set_image(url=res.image_url))
     source = paginator.EmbedSource(embeds)
     await paginator.CatchAllMenu(source=source).start(ctx)
Ejemplo n.º 14
0
    async def order(self, ctx, *, args=None):
        if args is None:
            await ctx.send("You can't order nothing.")
        if args:
            time_before = time.process_time()
            image_client = async_cse.Search(
                os.environ["image_api_key"],
                engine_id=os.environ["google_image_key"])
            try:
                results = await image_client.search(args,
                                                    safesearch=True,
                                                    image_search=True)
                emoji_image = sorted(
                    results,
                    key=lambda x: SequenceMatcher(None, x.image_url, args).
                    ratio(),
                )[-1]
            except async_cse.search.NoResults:
                await ctx.send("No results found :(")
                await image_client.close()
                return

            await image_client.close()
            time_after = time.process_time()
            try:
                await ctx.message.delete()
            except discord.errors.Forbidden:
                pass

            embed = discord.Embed(
                title=f"Item: {args}",
                description=f"{ctx.author} ordered a {args}",
                color=random.randint(0, 16777215),
                timestamp=ctx.message.created_at,
            )
            embed.set_author(name=f"order for {ctx.author}:",
                             icon_url=(ctx.author.avatar_url))
            embed.add_field(name="Time Spent:",
                            value=f"{int((time_after - time_before)*1000)}MS")
            embed.add_field(name="Powered by:", value="Google Images Api")
            embed.set_image(url=emoji_image.image_url)
            embed.set_footer(
                text=f"{ctx.author.id} \nCopyright: I don't know the copyright."
            )
            await ctx.send(
                content=
                "Order has been logged for safety purposes(we want to make sure no unsafe search is sent)",
                embed=embed,
            )
            await self.client.get_channel(738912143679946783).send(embed=embed)
Ejemplo n.º 15
0
 def __init__(self, bot):
     self.bot = bot
     self.google_client = async_cse.Search(GCS_DEVELOPER_KEY)
     self.icon = "💃"
     self.gender_icon = {
         "F": ":female_sign: ",
         "M": ":male_sign: ",
     }
     with open("data/data.json", "r") as f:
         data = json.load(f)
         try:
             self.artist_list = data["artists"]
         except KeyError:
             self.artist_list = []
Ejemplo n.º 16
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.remove_command('help')
     self._commands = 0
     self.currency_cache = {}
     self.session = ClientSession(loop=self.loop)
     self.dag = Client(dagpi_token, loop=self.loop)
     self.mystbin = mystbin.Client()
     self._start = time.time()
     self._prefixes = json.load(open('./prefixes.json', 'r'))
     self._banned = json.load(open('./bans.json', 'r'))
     self._edit_cache = {}
     self.cse = cse.Search(google_key)
     self.ipc = ipc.Server(self, 'localhost', 8080, secret_key=ipc_key)
     self.ball = ball()
     self.load_extension('jishaku')
     os.environ["JISHAKU_NO_UNDERSCORE"] = "true"
     os.environ["JISHAKU_NO_DM_TRACEBACK"] = "true"
     os.environ["JISHAKU_HIDE"] = "true"
Ejemplo n.º 17
0
async def main():
    """Starts the Search session."""

    google = async_cse.Search("Your API key")
    try:
        results = await google.search(input("Type something to Google it! "))
    except async_cse.NoResults:
        print("Nothing found.")
        return
    except async_cse.NoMoreRequests:
        print("API is out of requests, please use another API key.")
    except async_cse.APIError:
        print("Something went wrong.")
    else:
        for result in results:
            print(result.title)
            print(result.description)
            print("\n", result.url)
            input("\n\nPress enter to go to next result.")
    await main()
Ejemplo n.º 18
0
Archivo: api.py Proyecto: Narfee/neo
 async def google(self, ctx, *, query: str):
     """
     Search Google for the query
     """
     embeds = []
     async with ctx.loading(tick=False):
         keys = neo.secrets.gsearch_keys
         cli = cse.Search(keys, session=self.bot.session)
         res = await cli.search(query)
         embeds = build_google_embeds(res, show_images=False)
     if not embeds:
         return
     source = PagedEmbedMenu(embeds)
     menu = CSMenu(
         source,
         delete_on_button=True,
         clear_reactions_after=True,
         has_permissions={"administrator": True},
     )
     await menu.start(ctx)
Ejemplo n.º 19
0
Archivo: api.py Proyecto: mortalsky/neo
 async def image(self, ctx, *, query: str):
     """
     Search Google Images for the query
     """
     embeds = list()
     async with ctx.loading(tick=False):
         keys = os.getenv('IMAGE_TOKENS').split(',')
         cli = cse.Search(list(keys))
         res = await cli.search(query, image_search=True)
         results = [
             GoogleResults(title=result.title,
                           description=result.description,
                           result_url=result.url,
                           image_url=result.image_url) for result in res
         ]
         embeds = build_google_embeds(results)
     await cli.close()
     if not embeds:
         return
     source = PagedEmbedMenu(embeds)
     menu = CSMenu(source, delete_message_after=True)
     await menu.start(ctx)
Ejemplo n.º 20
0
    async def get_search(self, ctx, query, is_image=False):
        await ctx.trigger_typing()
        is_safe = True if not ctx.channel.is_nsfw() else False

        try:
            result = await self.bot.google.search(query=query,
                                                  image_search=is_image,
                                                  safesearch=is_safe)
        except async_cse.NoMoreRequests:
            try:
                self.bot.google = async_cse.Search(
                    api_key=next(self.bot.google_api_keys))
                result = await self.bot.google.search(query=query,
                                                      image_search=is_image,
                                                      safesearch=is_safe)
            except (async_cse.NoMoreRequests, StopIteration):
                raise NoMoreAPIKeys()
        except async_cse.NoResults as e:
            raise commands.BadArgument(" ".join(e.args))

        try:
            return random.choice(result[:5])
        except IndexError:
            raise commands.BadArgument("No results.")
Ejemplo n.º 21
0
 def __init__(self, bot):
     self.bot = bot
     self.google = async_cse.Search("API KEY HERE")  # insert your key here
Ejemplo n.º 22
0
 def __init__(self, bot):
     self.bot = bot
     self.google = async_cse.Search(self.bot.google_api_key)
Ejemplo n.º 23
0
import random
import jishaku
import asyncio
import json
from googletrans import Translator
import PyDictionary
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
translator = Translator(service_urls=['translate.googleapis.com'])
dictionary = PyDictionary.PyDictionary()

API = "AIzaSyDUW5x46SpqWVJTTnphKdP2_txtJwQBpCQ"
youtubeservice = build('youtube', version='v3', developerKey=API)
GOOGLE_API_KEY = "AIzaSyAfGRWztikfvzMEQ9sLQVkujcPHX19xVso"
engine = async_cse.Search(GOOGLE_API_KEY)

bot = commands.Bot(command_prefix="-")


class LolException(Exception):
    pass


class MyMenu(menus.Menu):
    def __init__(self, pages):
        super().__init__()
        self.pages: list = pages
        self.current_page: int = 0

    async def send_initial_message(self, ctx: commands.Context,
Ejemplo n.º 24
0
import async_cse
import asyncio
import os

API_KEY = os.environ.get("API_KEY")
client = async_cse.Search(API_KEY)


async def main():
    result = (await client.search("deepfried meme", image_search=True))[0]
    await client.search("deepfried meme")
    await client.close()
    print(result.title)
    print(result.description)
    print(result.image_url)
    print(result.url)


asyncio.get_event_loop().run_until_complete(main())
Ejemplo n.º 25
0
 def __init__(self, bot: Kurisu):
     self.bot = bot
     self.cse_session = async_cse.Search(
         self.bot.config.get("google_api_key"))
Ejemplo n.º 26
0
 def __init__(self, client):
     self.client = client
     self.googlethingy = async_cse.Search(self.client.data["gapikey"])