4
\$\begingroup\$

I'm actually developing bot in discord.py and the longer I'm developing this, the more often I'm asking myself 'Is this code well-organized? How could I improve this to make easier to understand this code in future?'

There's code:

from reddit_memes import *
from new_video_checker import *
from mmorpg_checker import *
from discord.ext import commands,tasks
import discord
import random
import time

class MyClient(commands.Bot):
    async def on_ready(self):
        start = time.time()
        print(f"Logged on {self.user}")
        print(self.user.id)
        print(self.user.name)
        await get_meme()
        await get_animeme()
        end = time.time()
        print(f"Start of bot took {round(end - start, 2)} seconds...")



MemeBot = MyClient(command_prefix='$')



@tasks.loop(hours=24)
async def renew_list():
    if renew_list.current_loop!=0:
        await get_meme()
        await get_animeme()


#meme() get random post from earlier generated list of posts and get from them few values - name,url,upvotes and comments
#which is used to print it lately in discord message.

@MemeBot.command()
async def meme(ctx):
    print(len(posts))
    random_post = random.choice(posts)
    posts.remove(random_post)
    name = random_post.title
    url = random_post.url
    ups = random_post.score
    permalink = f"https://www.reddit.com{random_post.permalink}"
    comments = random_post.num_comments
    if len(posts)<10:
        await get_meme()
    embed = discord.Embed(title=name,color=1146986)
    embed.set_image(url=url)
    embed.set_footer(text=f"👍:{ups} ⌨️:{comments}")
    embed.add_field(name="Source ⤵", value=f"[Click for redirect to page]({permalink})")
    await ctx.channel.send(embed=embed)

@MemeBot.command()
async def animeme(ctx):
    random_post = random.choice(ani_posts)
    ani_posts.remove(random_post)
    name,url,ups,comments=random_post.title,random_post.url,random_post.score,random_post.num_comments
    permalink = f"https://www.reddit.com{random_post.permalink}"
    if len(posts) < 10:
        await get_meme()
    embed= discord.Embed(title=f'Dla weebów {name}',color=10181046)
    embed.set_image(url=url)
    embed.set_footer(text=f"👍:{ups} ⌨️:{comments}")
    embed.add_field(name="Source ⤵" ,value=f"[Click for redirect to page]({permalink})")
    await ctx.channel.send(embed=embed)




yt_id = 'UCpnkp_D4FLPCiXOmDhoAeYA'
r =checker(yt_id)
current_vid_name =r['items'][0]['snippet']['title']

@tasks.loop(minutes=1)
async def video_checker():
    global current_vid_name
    channel_to_send = 885912169382834226
    channel_id =  MemeBot.get_channel(channel_to_send)

    if updater(yt_id,current_vid_name) != None:
        response = checker(yt_id)
        new_vid_name,new_vid_img,new_vid_url = getter(response)
        embed = discord.Embed(title=f"Memes arrived!",color=10181046)
        embed.set_image(url=new_vid_img)
        embed.set_footer(text=f"{new_vid_name}")
        embed.add_field(name="Source ⤵️",value=f'[Click for redirect to page]({new_vid_url})',inline=True)

        current_vid_name = new_vid_name
        print(current_vid_name)
        await channel_id.send(embed=embed)


@video_checker.before_loop
async def before_video_checker():
    print('Waiting for bot...')
    await MemeBot.wait_until_ready()
    await asyncio.sleep(30)


o_name,o_url = mmorpg_scrape()
o_img = mmorpg_post_image(url)
@tasks.loop(minutes=1)
async def mmorpg_news():
    channel_to_send = 886651440658022400
    channel_id = MemeBot.get_channel(channel_to_send)
    n_name, n_url = mmorpg_scrape()
    n_img = mmorpg_post_image(url)
    if n_name!=o_name:
        embed = discord.Embed(title=f"News:{name}" ,color=9807270)

        if n_img!=None:
            embed.set_image(url=n_img)
        embed.add_field(name="Source ⤵️", value=f'[Click for redirect to page]({url})', inline=True)
        await channel_id.send(embed=embed)
@mmorpg_news.before_loop
async def before_mmorpg_news():
    await MemeBot.wait_until_ready()
    await asyncio.sleep(45)

@MemeBot.command()
async def h(ctx):
    message =f"""  
Commands:                    
$meme,$animeme               
                      
Running in background:       
video_checker,mmorpg_news    
    """
    await ctx.send(message)

renew_list.start()
video_checker.start()
mmorpg_news.start()
MemeBot.run(secure)

Is meme() function well described? Or should I describe it more precisely?

I would be thankful if you would give me few tips :)

\$\endgroup\$
3
  • \$\begingroup\$ FYI, about dpy: gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1 \$\endgroup\$
    – GammaGames
    Sep 14 at 18:38
  • \$\begingroup\$ @GammaGames Well,I heard about this before started developing my bot using this library.It's probably waste of time learning how to use it,my purpose is to learn new things like working with dictionaries ,json or OOP in practice instead of reading about it. It's probably useless for usage in portfolio but kinda funny \$\endgroup\$
    – Vipek
    Sep 14 at 19:18
  • 1
    \$\begingroup\$ Nah, I figured you were using it to learn and learning is never wasted time. Those skills will be helpful! There's a few active dpy forks anyway, the community just needs some time to figure out who comes out on top. \$\endgroup\$
    – GammaGames
    Sep 14 at 19:36
4
\$\begingroup\$

You shouldn't use comments to describe your function, but docstrings.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thanks ,I saw people using this when started learning python ,but thought it was just comment. \$\endgroup\$
    – Vipek
    Sep 14 at 10:31
4
\$\begingroup\$

Where does stdout (print) go when this is being run as it would in "real life", unsupervised in production? If the answer is "nowhere useful", then you should be using the logging framework instead of print.

Don't use time.time() for performance analysis; you need it to be monotonic.

Rewrite colour literal 1146986 as 0x11806A and so on for your other colours.

Use is not None instead of != None due to None being a singleton in Python.

It doesn't seem like a good idea to hard-code channel IDs like 886651440658022400 in your source. That should be externalized to a config file, or at the least, called out in a global constant.

\$\endgroup\$
3
  • \$\begingroup\$ Thank you very much! I was going to learn logging but when i started programming in Python last month it looked pretty difficult for me and instead of spending time on learning things like this I decided to start doing small projects I really appreciate Your detailed answer! Btw why use 0x.... instead of int (just curious) \$\endgroup\$
    – Vipek
    Sep 14 at 19:03
  • 1
    \$\begingroup\$ It makes the colour balance more clear just by looking at it - the red, green and blue fields are each one byte (two hexits). \$\endgroup\$
    – Reinderien
    Sep 14 at 19:30
  • \$\begingroup\$ While logging is good to get to know, I've seen loguru used recently and it seems like a good simple alternative. \$\endgroup\$
    – TylerW
    Sep 15 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.