コード例 #1
0
async def main():
    if "praw_client_id" not in os.environ:
        sys.stderr.write("Environment variable ``praw_client_id`` must be defined\n")
        return 1
    if "praw_client_secret" not in os.environ:
        sys.stderr.write(
            "Environment variable ``praw_client_secret`` must be defined\n"
        )
        return 1

    await initialize_refresh_token_file()

    refresh_token_manager = FileTokenManager(REFRESH_TOKEN_FILENAME)
    async with asyncpraw.Reddit(
        token_manager=refresh_token_manager,
        user_agent="use_file_token_manager/v0 by u/bboe",
    ) as reddit:

        scopes = await reddit.auth.scopes()
        if scopes == {"*"}:
            print(f"{await reddit.user.me()} is authenticated with all scopes")
        elif "identity" in scopes:
            print(
                f"{await reddit.user.me()} is authenticated with the following scopes: {scopes}"
            )
        else:
            print(f"You are authenticated with the following scopes: {scopes}")
コード例 #2
0
ファイル: nsfw.py プロジェクト: K-209/Meifwa-Discord-Bot
    async def thickhentai(self, ctx):
        r = asyncpraw.Reddit(client_id="myVr7vToLuADLQLCMBrfpQ",
                             client_secret=self.bot.get_config(
                                 "config", "config", "reddit_secret"),
                             user_agent="meifwa")

        subreddit = await r.subreddit("thick_hentai")
        all_subs = []
        top = subreddit.top(limit=50)
        async for submission in top:
            all_subs.append(submission)

        random_sub = random.choice(all_subs)
        url = random_sub.url

        embed = discord.Embed(
            title=f"r/{subreddit}",
            description=
            f"[{submission.title}](https://reddit.com{submission.permalink})",
            color=ctx.message.author.color,
            timestamp=ctx.message.created_at)
        embed.set_image(url=url)
        embed.set_author(name="Requested By: " + str(ctx.message.author),
                         icon_url=ctx.message.author.avatar.url)
        embed.set_footer(
            text=
            f"{submission.score} points | {submission.num_comments} comments")
        await ctx.reply(embed=embed)
コード例 #3
0
ファイル: reddit.py プロジェクト: Quintec/The-Jambot
 def __init__(self, client):
     self.client = client
     self.reddit = praw.Reddit(client_id=client_id,
                               client_secret=client_secret,
                               username=username,
                               password=password,
                               user_agent="thejambot")
コード例 #4
0
 def _get_praw_instance(self):
     r = asyncpraw.Reddit(user_agent=self.user_agent,
                          client_id=self.config.client_id,
                          client_secret=self.config.client_secret,
                          username=self.config.username,
                          password=self.config.password)
     return r
コード例 #5
0
    async def init(self):
        await self.bot.wait_until_red_ready()
        if await self.config.SCHEMA_VERSION() == 1:
            data = await self.config.all_channels()
            for channel, _ in data.items():
                async with self.config.channel_from_id(
                        channel).reddits() as sub_data:
                    for feed in sub_data:
                        try:
                            sub_data[feed]["subreddit"] = sub_data[feed][
                                "url"].split("/")[4]
                        except IndexError:
                            sub_data[feed]["subreddit"] = None
            await self.bot.send_to_owners(
                "Hi there.\nRedditPost has now been given an update to accomodate the new reddit ratelimits. This cog now requires authenthication.\nTo setup the cog create an application via https://www.reddit.com/prefs/apps/. Once this is done, copy the client ID found under the name and the secret found inside.\nYou can then setup this cog by using `[p]set api redditpost clientid CLIENT_ID_HERE clientsecret CLIENT_SECRET_HERE`\n"
            )
            await self.config.SCHEMA_VERSION.set(2)

        token = await self.bot.get_shared_api_tokens("redditpost")
        try:
            self.client = asyncpraw.Reddit(
                client_id=token.get("clientid", None),
                client_secret=token.get("clientsecret", None),
                user_agent=f"{self.bot.user.name} Discord Bot",
            )

            self.bg_loop_task = self.bot.loop.create_task(self.bg_loop())
        except Exception as exc:
            log.error("Exception in init: ", exc_info=exc)
            await self.bot.send_to_owners(
                "An exception occured in the authenthication. Please ensure the client id and secret are set correctly.\nTo setup the cog create an application via https://www.reddit.com/prefs/apps/. Once this is done, copy the client ID found under the name and the secret found inside.\nYou can then setup this cog by using `[p]set api redditpost clientid CLIENT_ID_HERE clientsecret CLIENT_SECRET_HERE`"
            )
コード例 #6
0
ファイル: reddit.py プロジェクト: SSagun-c/Hugo.py
    async def wouldyourather(self, ctx):
        reddit = asyncpraw.Reddit(client_id=os.environ['RAI'],
                                  client_secret=os.environ['RAS'],
                                  username=os.environ['user'],
                                  password=os.environ['pass'],
                                  user_agent='SSagunPraw')

        subreddit = await reddit.subreddit("wouldyourather")
        all_subs = []

        top = subreddit.top(limit=100)

        async for submission in top:
            all_subs.append(submission)

        random_sub = random.choice(all_subs)

        name = random_sub.title

        embed = discord.Embed(title=name, color=0xEEEEEE)

        embed.set_author(name='Would you Rather?')
        embed.timestamp = datetime.datetime.utcnow()

        embed.set_footer(text=f"Would you rather...this.. or... this?")

        await ctx.send(embed=embed)
コード例 #7
0
        async def get_sub_futures(sub_ids: List[str],
                                  reddit_details: dict) -> tuple:
            # make each sub_id request into a future and
            # gather all futures together into a tuple

            # have to include init of reddit object inside the async loop
            # else async loop raise an error. Should improve this fix :/

            # Something has to be done with Timeouts due to large
            # number of concurrent requests. Adding try/excepts on each
            # request in get_submission function seems lame. Maybe solve
            # this with custom client with limited concurrent connections:
            # aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=10))
            reddit = asyncpraw.Reddit(**reddit_details,
                                      requestor_class=Requestor,
                                      requestor_kwargs={
                                          'session':
                                          ClientSession(connector=TCPConnector(
                                              limit=5000))
                                      })

            # use context or else the session above will not be closed
            # and warning/errors will pop for each request or session
            async with reddit:
                tasks = set()
                for id in sub_ids:
                    tasks.add(
                        asyncio.create_task(
                            self._parse_single_submission(
                                reddit.submission(id))))
                return await asyncio.gather(*tasks)
コード例 #8
0
    def __init__(self, bot):
        self.bot = bot
        self.base_url = "https://www.reddit.com"

        reddit_login = IO.read_settings_as_json()
        reddit_data = reddit_login['reddit']

        username = reddit_data['username']
        password = reddit_data['password']
        client_id = reddit_data['client_id']
        client_secret = reddit_data['client_secret']
        user_agent = reddit_data['user_agent']
        self.post_title = reddit_data['post_title']
        self.post_url = reddit_data['post_url']

        if username is None or password is None or client_id is None or client_secret is None or user_agent is None or \
                self.post_title is None or self.post_url is None:
            cmds = Reddit.get_commands(self)
            for cmd in cmds:
                cmd.update(enabled=False)
        else:
            self.reddit = asyncpraw.Reddit(
                username=username,
                password=password,
                client_id=client_id,
                client_secret=client_secret,
                user_agent=user_agent
            )
コード例 #9
0
    def __init__(self, command_prefix, **options):
        super().__init__(command_prefix, **options)

        pgloop = asyncio.get_event_loop()
        f = pickle.load(open('credentials.pkl', 'rb'))
        self.pool = pgloop.run_until_complete(
            asyncpg.create_pool(dsn=f["postgres_uri"],
                                host=f["postgres_host"],
                                user=f["postgres_user"],
                                port=f["postgres_port"],
                                password=f["postgres_password"],
                                database=f["postgres_database"]))

        self.reddit = apraw.Reddit(client_id=f['reddit_id'],
                                   client_secret=f['reddit_secret'],
                                   user_agent="Eclipse")
        self.memes = []
        self.brain_id = f['brain_id']
        self.brain_api = f['brain_api']
        self.token = f["discord"]
        self.sra_api = f['some_random_api']
        self.launch_time = datetime.datetime.utcnow()
        self.gameboy = False
        self.color = discord.Color.from_rgb(156, 7, 241)
        with open("config/config.json", "r") as read_file:
            data = json.load(read_file)
            self.config = data
        self.flask_instance: Flask = None
        self.flask_thread: multiprocessing.Process = None
コード例 #10
0
    async def meme_quote(self, ctx):
        reddit = asyncpraw.Reddit(
            client_id="cv4eeeqKG-IseA",
            client_secret="t3O9tFzRXpYybwLAn4cquJ2QKgLh2Q",
            username="******",
            password="******",
            user_agent="eleop")

        subreddit = reddit.subreddit("memes")
        all_subs = []

        top = subreddit.top(limit=50)

        for submission in top:
            all_subs.append(submission)

        random_sub = choice(all_subs)

        name = random_sub.title
        url = random_sub.url

        embed = Embed(title=name)

        embed.set_image(url=url)
        embed.set_footer(text=f"Requested by {ctx.author}",
                         icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed)
コード例 #11
0
    async def get_hot_subreddit_images(self, sub_reddit: str, posts_limit: int,
                                       num: int) -> list:
        """Gets a list of subreddit pics

        Args:
            sub_reddit (str): subreddit to get pics from
            pics_limit (int): num of pics to charge
            num (int): num of pics to return

        Returns:
            list: containing reddit posts
        """
        reddit = asyncpraw.Reddit(
            client_id=self.client_id,
            client_secret=self.client_secret,
            user_agent=self.user_agent,
            check_for_async=False,
        )

        subreddit = await reddit.subreddit(sub_reddit)
        hot_posts = subreddit.hot(limit=posts_limit)

        posts = []
        async for post in hot_posts:
            if "jpg" in post.url or "png" in post.url and not post.over_18:
                posts.append(post.url)
        await reddit.close()
        return posts
コード例 #12
0
async def get_cogcision() -> str:
    reddit = asyncpraw.Reddit(
        client_id=REDDIT_ID,
        client_secret=REDDIT_SECRET,
        user_agent="prawddit",
    )

    subreddit = await reddit.subreddit("wallstreetbets")

    symbol_list = []

    async for comment in subreddit.comments(limit=10000000):
        words = comment.body.split()
        for word in words:
            if len(word) in range(1, 5) or (word[0] == "$"):
                symbol = True
                for c in word:
                    if c.islower() or not c.isalpha():
                        symbol = False

                if symbol:
                    symbol_list.append(word)

    async for comment in subreddit.new(limit=10000000):
        words = comment.title.split()
        for word in words:
            if len(word) in range(1, 5) or (word[0] == "$"):
                symbol = True
                for c in word:
                    if c.islower() or not c.isalpha():
                        symbol = False

                if symbol:
                    symbol_list.append(word)

    counter = 0
    while True:
        # randomly pick a stock
        symbol = random.choice(symbol_list)
        try:
            print(f"trying {symbol}")
            stock = api.get_last_trade(symbol)
            break
        except:
            counter += 1
            if counter == 100:
                return "SORRY IM TOO WEAK. THESE FOOLS ARE SPEWING BULLSHIT."
                break
            pass

    # # randomly pick buy/sell
    action = random.choice(["BUY", "SELL"])

    # # randomly pick amount
    amount = random.randint(1, 100)

    # # return sentence
    return (
        f"I WILL {action} {amount} SHARE{'S' if amount >= 1 else ''} OF {symbol}. THIS LITTLE MANEUVER IS GONNA COST US $"
        + str(stock.price * amount))
コード例 #13
0
 def cog_load(self):
     self.reddit = asyncpraw.Reddit(client_id=self.tokens['reddit'][0],
                                    client_secret=self.tokens['reddit'][1],
                                    user_agent=self.options['useragent'])
     self.subreddit = None
     self.auto_refresh.change_interval(
         minutes=self.options['refresh_interval'])
     self.auto_refresh.start()
コード例 #14
0
 def __init__(self, bot):
     self.bot = bot
     self.reddit = asyncpraw.Reddit(
         client_id = os.environ['REDDIT_APP_ID'],
         client_secret = os.environ['REDDIT_APP_SECRET'],
         user_agent = f"speedwagon-discord-bot:{os.environ['REDDIT_APP_ID']}:1.0",
         check_for_async = False
     )
コード例 #15
0
ファイル: vredditdl.py プロジェクト: owldyn/owlcogs
 def __init__(self, bot):
     """set it up"""
     super().__init__()
     self.bot = bot
     self.reddit = praw.Reddit(
         "Hoobot", user_agent="discord:hoobot:1.0 (by u/owldyn)")
     self.conf = Config.get_conf(self, identifier=26400735)
     self.conf.register_global(**self.default_global_settings)
コード例 #16
0
 def __init__(
         self,
         bot):  # This allows the cog to access the bot, and its functions
     self.bot = bot
     self.reddit = asyncpraw.Reddit(
         client_id=os.environ["REDDIT_CLIENT_ID"],
         client_secret=os.environ["REDDIT_CLIENT_SECRET"],
         user_agent=os.environ["REDDIT_USER_AGENT"])
コード例 #17
0
ファイル: Reddit.py プロジェクト: rkpop/kokobot
 def __init__(self, config):
     self.reddit = asyncpraw.Reddit(
         client_id=config["Reddit"]["ClientID"],
         client_secret=config["Reddit"]["ClientSecret"],
         password=config["Reddit"]["Password"],
         user_agent="KoKoBot/0.1 by Kilenaitor",
         username=config["Reddit"]["Username"],
     )
コード例 #18
0
ファイル: reddit.py プロジェクト: senseidevs/Tortoise-BOT
 def __init__(self, bot):
     self.bot = bot
     self.reddit = asyncpraw.Reddit(
         client_id=os.getenv("PRAW_CLIENT_ID"),
         client_secret=os.getenv("PRAW_CLIENT_SECRET"),
         user_agent="Tortoise Discord Bot",
     )
     self._cache = RedditPostsCache()
コード例 #19
0
def setup(client):
    client.add_cog(
        games(client,
              reddit=asyncpraw.Reddit(client_id=reddit_client_id,
                                      client_secret=reddit_client_secret,
                                      username=reddit_username,
                                      password=reddit_password,
                                      user_agent=reddit_user_agent)))
コード例 #20
0
async def main():
    """Provide the program's entry point when directly executed."""
    print(
        "Go here while logged into the account you want to create a token for: "
        "https://www.reddit.com/prefs/apps/")
    print(
        "Click the create an app button. Put something in the name field and select the"
        " script radio button.")
    print(
        "Put http://localhost:8080 in the redirect uri field and click create app"
    )
    client_id = input(
        "Enter the client ID, it's the line just under Personal use script at the top: "
    )
    client_secret = input(
        "Enter the client secret, it's the line next to secret: ")
    commaScopes = input(
        "Now enter a comma separated list of scopes, or all for all tokens: ")

    if commaScopes.lower() == "all":
        scopes = ["*"]
    else:
        scopes = commaScopes.strip().split(",")

    reddit = asyncpraw.Reddit(
        client_id=client_id.strip(),
        client_secret=client_secret.strip(),
        redirect_uri="http://localhost:8080",
        user_agent="praw_refresh_token_example",
    )
    state = str(random.randint(0, 65000))
    url = reddit.auth.url(scopes, state, "permanent")
    print("Now open this url in your browser: " + url)
    sys.stdout.flush()

    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value
        for (key, value) in [token.split("=") for token in param_tokens]
    }

    if state != params["state"]:
        send_message(
            client,
            f"State mismatch. Expected: {state} Received: {params['state']}",
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

    refresh_token = await reddit.auth.authorize(params["code"])
    send_message(client, f"Refresh token: {refresh_token}")
    await reddit._http.close()
    return 0
コード例 #21
0
ファイル: reddit.py プロジェクト: SSagun-c/Hugo.py
    async def _reddit(self, ctx, subred="meme"):  # default subreddit is meme
        reddit = asyncpraw.Reddit(client_id=os.environ['RAI'],
                                  client_secret=os.environ['RAS'],
                                  username=os.environ['user'],
                                  password=os.environ['pass'],
                                  user_agent='SSagunPraw')

        subreddit = await reddit.subreddit(subred)
        all_subs = []

        top = subreddit.top(limit=75)

        async for submission in top:
            all_subs.append(submission)

        random_sub = random.choice(all_subs)

        if submission.over_18 == True:
            if ctx.channel.is_nsfw:
                sr_name = random_sub.subreddit
                author = random_sub.author
                name = random_sub.title
                url = random_sub.url

                embed = discord.Embed(title=author,
                                      description=name,
                                      color=0xFF4500)
                embed.set_author(
                    name=f'r/{sr_name}',
                    url=url,
                    icon_url='https://i.postimg.cc/pTzSdRqC/reddit-logo.png')
                embed.set_image(url=url)
                embed.timestamp = datetime.datetime.utcnow()
                embed.set_footer(
                    text=
                    f"If the Image is not loading just click on r/{sr_name}!")
                await ctx.send(embed=embed)
            else:
                await ctx.send("Sorry but this subreddit is marked as NSFW!")
        else:
            sr_name = random_sub.subreddit
            author = random_sub.author
            name = random_sub.title
            url = random_sub.url

            embed = discord.Embed(title=author,
                                  description=name,
                                  color=0xFF4500)
            embed.set_author(
                name=f'r/{sr_name}',
                url=url,
                icon_url='https://i.postimg.cc/pTzSdRqC/reddit-logo.png')
            embed.set_image(url=url)
            embed.timestamp = datetime.datetime.utcnow()
            embed.set_footer(
                text=f"If the Image is not loading just click on r/{sr_name}!")
            await ctx.send(embed=embed)
コード例 #22
0
 async def memes(self, ctx):
     reddit = asyncpraw.Reddit(client_id=f'{meme()[0]}',
                               client_secret=f'{meme()[1]}',
                               user_agent=f'{meme()[2]}')
     memes_submissions = await reddit.subreddit('memes').hot()
     post_to_pick = random.randint(1, 20)
     for i in range(0, post_to_pick):
         submission = next(x for x in memes_submissions if not x.stickied)
     await ctx.send(submission.url)
コード例 #23
0
    def __init__(self, bot):
        self.bot = bot

        self.bot.logger.debug("Starting reddit client.")
        conf = bot.get_config_value('reddit')
        self.reddit_client = asyncpraw.Reddit(**conf._asdict())

        self.scanners = (RedditScanner(self), )
        self.scan_all_feeds.start()
コード例 #24
0
def setup(bot: ButtercupBot) -> None:
    """Set up the Rules cog."""
    reddit_config = bot.config["Reddit"]
    reddit_api = asyncpraw.Reddit(
        client_id=reddit_config["client_id"],
        client_secret=reddit_config["client_secret"],
        user_agent=reddit_config["user_agent"],
    )
    bot.add_cog(Rules(bot=bot, reddit_api=reddit_api))
コード例 #25
0
ファイル: wsb.py プロジェクト: pepimartinez/wsbscraper
async def reddit_instance():
    """
    Return instance of Reddit
    """
    reddit = asyncpraw.Reddit(
        client_id=os.getenv('REDDIT_CLIENT_ID'),
        client_secret=os.getenv('REDDIT_CLIENT_SECRET'),
        user_agent=os.getenv('REDDIT_USER_AGENT'),
    )
    return reddit
コード例 #26
0
 def __init__(self, bot):
     logger.info(Constants.COG_STARTUP, Constants.FUN)
     self.bot = bot
     # Reddit API id and secret is stored within my PRAW's praw.ini as [nezuko] entry.
     praw_secrets = get_praw_secrets()
     self.reddit = asyncpraw.Reddit(user_agent=Constants.NEZUKO_BOT,
                                    client_id=praw_secrets[0],
                                    client_secret=praw_secrets[1])
     self.subreddits = Constants.MEME_SUBREDDITS
     self.uwu_subreddits = Constants.UWU_SUBREDDITS
コード例 #27
0
 def __init__(self) -> None:
     self.colour = Colour.purple()
     self.historyEventsTable = json.loads(
         open(historyEventsPath, "r").read())
     self.redditClient = asyncpraw.Reddit(
         client_id=Config.redditID,
         client_secret=Config.redditSecret,
         user_agent="linux:LiSBot:1.0 (by u/JackAshwell1)")
     self.bot = None
     self.posts = None
コード例 #28
0
 def __init__(self, bot):
     self.bot = bot
     self.engine = cse.Search(self.bot.config['googleapikey'])
     self.client = sr_api.Client()
     self.reddit = asyncpraw.Reddit(
         client_id=self.bot.config['redditauth'][1],
         client_secret=self.bot.config['redditauth'][0],
         password=self.bot.config['password'],
         user_agent=self.bot.config['redditauth'][2],
         username="******")
コード例 #29
0
 async def get_sub_images(self, subreddit, num=50, invalid_ids=None):
     self.reddit = asyncpraw.Reddit(site_name="WardenBotScraper",
                                    user_agent="Warden User Agent")
     print(f"get_sub_images was called! Subreddit: {subreddit}! Num: {num}")
     if await self.sub_available(subreddit):
         print("Valid Sub!")
         self.subreddit = await self.reddit.subreddit(subreddit)
     else:
         self.subreddit = await self.reddit.random_subreddit(nsfw=False)
         self.error_flag = True
         print(
             f"Invalid Subreddit, Random One Assigned: {self.subreddit.display_name}!"
         )
     self.sub_name = self.subreddit.display_name
     post = None
     if await self.subreddit.random() is not None:
         print("Getting random post!")
         for i in range(num):
             submission = await self.subreddit.random()
             if not test_post(submission):
                 pass
             else:
                 if invalid_ids:
                     if submission.id in invalid_ids:
                         pass
                     else:
                         print("Post appended!")
                         post = submission.url
                         break
                 else:
                     print("Post appended!")
                     post = submission.url
                     break
     else:
         async for submission in self.subreddit.hot(limit=num):
             if not test_post(submission):
                 pass
             else:
                 if invalid_ids:
                     if submission.id in invalid_ids:
                         print("Invalid id!")
                     else:
                         print("Post appended!")
                         post = submission.url
                         break
                 else:
                     print("Post appended!")
                     post = submission.url
                     break
     await self.reddit.close()
     if not post:
         self.no_img_flag = True
         return await self.get_sub_images(None)
     else:
         return post
コード例 #30
0
 def __init__(self, bot: "Bot"):
     self.bot = bot
     self.subs = ("dankmemes", "memes", "wholesomememes")
     self.posted = {}
     self.reddit = asyncpraw.Reddit(
         client_id=os.environ.get('REDDITCLIENTID'),
         client_secret=os.environ.get('REDDITCLIENTSECRET'),
         password=os.environ.get('REDDITPASSWORD'),
         user_agent="Friday Discord bot v1.0.0  (by /u/Motostar19)",
         username="******")
     self.reddit.read_only = True