Wednesday, November 2, 2022
HomeWordPress DevelopmentTwitter Replying Bot that generates coloration grids

Twitter Replying Bot that generates coloration grids


Yet one more tweepy tutorial, however we aren’t complaining.

a little bit background: i prefer to create random fractals artwork (NFT anybody) I can simply can spend hours gazing one and seeing all various things. so what’s a greater strategy to share my creations? a twitter bot after all, however lets additionally make it do one thing else.

Preview

you possibly can strive it your self by tweeting ‘make grid’ to @machineation on twitter. the bot will hash your username then use it as a seed to generate a novel coloration grid primarily based on the username. lets begin.

necessities:

  • python >= 3.10
  • twitter developer account (not lined within the tutorial)
  • tweepy
  • numpy
  • pillow

in case your not aware of twitter developer account, please Test this as a result of creating the developer account, app, and getting the authentication will not be lined on this tutorial.

lets begin by putting in the required packages..be at liberty to make use of digital atmosphere or pip3 when you have each model of python.

pip set up tweepy numpy pillow
Enter fullscreen mode

Exit fullscreen mode

after every part is put in, lets create a file known as “bot.py” however you possibly can identify yours something you want, after which lets import what we’ll want.

import tweepy, random, time, os, pathlib, numpy, hashlib
from PIL import Picture
Enter fullscreen mode

Exit fullscreen mode

after that, we have to add the authentication and create the API object utilizing tweepy. you possibly can learn in regards to the tweepy authentication within the docs however essientially, you want the API Key, API Key Secret, Entry Token and Entry Token Secret

your keys are secret. do not embrace them within the script and add them to to any publicly seen cloud. use .env or another methodology to maintain secrets and techniques. for simplicity, the tutorial would not cowl that

auth = tweepy.OAuthHandler("xxxx", "xxxx")
auth.set_access_token("xxxx", "xxxx")

#create API object
api = tweepy.API(auth, wait_on_rate_limit=True)
Enter fullscreen mode

Exit fullscreen mode

  • wait_on_rate_limit – Whether or not or to not robotically look forward to charge limits to replenish

So as to not reply to the identical tweet a number of instances and in addition to get solely the mentions that the bot have not seen but, we’ll ensure that to avoid wasting the final point out tweet id. We are going to put it aside to a file in order that even when we stopped the bot after which resumed, we’ll begin from the mentions we’ve not seen but, not from the start.
Let’s create 2 capabilities. One for studying the id from file and one to retailer the id.

def read_last_seen(FILE_NAME):
  file_read = open(FILE_NAME,'r')
  last_seen_id = int(file_read.learn().strip())
  file_read.shut()
  return last_seen_id

def store_last_seen(FILE_NAME, last_seen_id):
  file_write = open(FILE_NAME,'w')
  file_write.write(str(last_seen_id))
  file_write.write("n")
  file_write.shut()
  return
Enter fullscreen mode

Exit fullscreen mode

Discover that the primary operate for studying the id takes one parameter which is the file identify, and the operate to retailer the id takes 2 parameters, the file identify and the id. sooner or later, if you wish to have extra capabilities that retailer and skim various things, you possibly can name the identical capabilities and altering the parameters and we might change “last_seen_id” with “knowledge” for instance.

Now, Lets create the operate to create the colours grid from the username. I opted to code it as a separate operate.

def make_grid(deal with):
    hash = int(hashlib.sha256(deal with.encode('utf-8')).hexdigest(), 16) % 10**8
    numpy.random.seed(hash)
    # Generate 100x100 grid of random colors
    grid = numpy.random.randint(0,256, (100,100,3), dtype=numpy.uint8)
    im = Picture.fromarray(grid).resize((1600,1600), resample=Picture.Resampling.NEAREST)

    im.save(os.path.be a part of(os.path.dirname(__file__), "grids/") + deal with + '.png')
Enter fullscreen mode

Exit fullscreen mode

  • “deal with”: the parameter that would be the username that we are going to move to the operate.
  • “hash”: we’ll hash the username utilizing sha256 to make use of it as a random seed for numpy.
  • “grid”: utilizing numpy, we create a grid with random colours (seeded with the username hash). you may make it any dimension you need.
  • “im”: utilizing pillow to create the 1600×1600 picture from the information. you need to use any dimension you need.

we then save the png picture in a folder in the identical listing known as “grids” with the username because the file identify.

Subsequent step, let’s create the operate that may:

  1. Fetch the mentions since final saved tweet id.
  2. Loop over the mentions.
  3. Retailer the tweet id.
  4. Test if the tweet just isn’t by our bot.
  5. Test if tweet comprises particular phrases.
  6. Test if the tweet would not include further phrases and reply with a message if that’s the case.
  7. Reply to tweet relying on the matched phrase.

this implies you possibly can broaden the bot to do different issues primarily based on the tweet content material (command). However first, we have to set some variables.

def grid_tweet():
    bot_id = xxxxxxxxxxxx
    FILE_NAME = os.path.be a part of(os.path.dirname(__file__), "grid_last_seen.txt")
    phrases = ["make grid"]
    message = "Right here is your distinctive coloration grid, @{}"
    grid_unknown = "@{} If you'd like a grid, You simply must tweet 'make grid' to Me with out some other phrases and I'll create and ship You one."
Enter fullscreen mode

Exit fullscreen mode

let’s go over them:



bot_id

we set this variable in order that we are able to test if the tweet creator just isn’t our bot. this manner we make it possible for if our bot tweeted the identical phrases we’re searching for, the bot would not reply to itself. you may get the bot id by means of other ways, however right here is an easy one

By the Browser
you possibly can go to the bot web page on twitter, proper click on anyplace contained in the web page and click on “Examine” then seek for “identifier” within the parts which is able to look one thing like this

"identifier": "1572580999673831426"



FILE_NAME

that is the file we’ll use to learn and retailer the final point out tweet id. This will likely be used to name the capabilities we already created and move the variable to them. We are able to then have completely different information for various capabilities if we wish.



phrases

The checklist of phrases we’re searching for. you possibly can add extra separated with a comma. For our instance we’re solely utilizing “make grid”.



message

the message we’re going to embrace in our reply. we’re utilizing {} on the finish to format it later and add the username to it.



grid_unknown

One other message if the tweet has further phrases along with “make grid”. additionally utilizing {} to be formatted later with the username.

now let’s create the remainder of the code.

    whereas True:
        # Discovering tweets that point out our bot
        mentions = api.mentions_timeline(since_id=read_last_seen(FILE_NAME)) 
        # Iterating by means of every point out tweet
        for point out in mentions:
            # Save the tweet id within the file
            store_last_seen(FILE_NAME, point out.id)
            # Test to see if the tweet creator just isn't our bot
            if point out.creator.id != bot_id:
                # Test if the tweet has any of the phrases we outlined in our checklist after changing the tweet to decrease case
                if True in [word in mention.text.lower() for word in words]:
                    # Removes the primary a part of the point out which is our bot username like so @username
                    command = point out.textual content.decrease().break up(' ',1)[1]
                    # Act primarily based on the matched phrase/command. can later be used so as to add extra performance.
                    match command:
                        case "make grid":
                            strive:
                                # Prints the username and tweet
                                print(f"{point out.creator.screen_name} - {point out.textual content}")
                                print('Creating Grid')
                                # Calls our make_grid operate and passing the username.
                                make_grid(point out.creator.screen_name)
                                # Set the media to the picture created by our operate
                                media = os.path.be a part of(os.path.dirname(__file__), "grids/") + point out.creator.screen_name + '.png'
                                print("Trying to answer...")
                                # Reply with the message after formatting to incorporate username and the media
                                api.update_status_with_media(message.format(point out.creator.screen_name), media, in_reply_to_status_id=point out.id_str)
                                print("Efficiently replied :)")
                            # Error dealing with. for now it simply prints the error.
                            besides Exception as exc:
                                print(exc)
                        # If the tweet comprises further phrases along with our command
                        case different:
                            strive:
                                print('tweet comprises different phrases')
                                # Reply with the grid_unknown message
                                api.update_status(grid_unknown.format(point out.creator.screen_name), in_reply_to_status_id=point out.id_str)
                                print("Efficiently replied with explaination :)")
                            besides Exception as exc:
                                print(exc)
        # Sleep for two minutes
        time.sleep(120)
Enter fullscreen mode

Exit fullscreen mode

so on the finish, our file will appear like this:

import tweepy, random, time, os, pathlib, numpy, hashlib
from PIL import Picture

auth = tweepy.OAuthHandler("xxxx", "xxxx")
auth.set_access_token("xxxx", "xxxx")

#create API object
api = tweepy.API(auth, wait_on_rate_limit=True)

def read_last_seen(FILE_NAME):
  file_read = open(FILE_NAME,'r')
  last_seen_id = int(file_read.learn().strip())
  file_read.shut()
  return last_seen_id

def store_last_seen(FILE_NAME, last_seen_id):
  file_write = open(FILE_NAME,'w')
  file_write.write(str(last_seen_id))
  file_write.write("n")
  file_write.shut()
  return    

def make_grid(deal with):
    hash = int(hashlib.sha256(deal with.encode('utf-8')).hexdigest(), 16) % 10**8
    numpy.random.seed(hash)
    # Generate 100x100 grid of random colors
    grid = numpy.random.randint(0,256, (100,100,3), dtype=numpy.uint8)
    im = Picture.fromarray(grid).resize((1600,1600), resample=Picture.Resampling.NEAREST)

    im.save(os.path.be a part of(os.path.dirname(__file__), "grids/") + deal with + '.png')
def grid_tweet():
    bot_id = xxxxxxxxxxxx
    FILE_NAME = os.path.be a part of(os.path.dirname(__file__), "grid_last_seen.txt")
    phrases = ["make grid"]
    message = "Right here is your distinctive coloration grid, @{}"
    grid_unknown = "@{} If you'd like a grid, You simply must tweet 'make grid' to Me with out some other phrases and I'll create and ship You one."
    whereas True:
        # Discovering tweets that point out our bot
        mentions = api.mentions_timeline(since_id=read_last_seen(FILE_NAME)) 
        # Iterating by means of every point out tweet
        for point out in mentions:
            # Save the tweet id within the file
            store_last_seen(FILE_NAME, point out.id)
            # Test to see if the tweet creator just isn't our bot
            if point out.creator.id != bot_id:
                # Test if the tweet has any of the phrases we outlined in our checklist after changing the tweet to decrease case
                if True in [word in mention.text.lower() for word in words]:
                    # Removes the primary a part of the point out which is our bot username like so @username
                    command = point out.textual content.decrease().break up(' ',1)[1]
                    # Act primarily based on the matched phrase/command. can later be used so as to add extra performance.
                    match command:
                        case "make grid":
                            strive:
                                # Prints the username and tweet
                                print(f"{point out.creator.screen_name} - {point out.textual content}")
                                print('Creating Grid')
                                # Calls our make_grid operate and passing the username.
                                make_grid(point out.creator.screen_name)
                                # Set the media to the picture created by our operate
                                media = os.path.be a part of(os.path.dirname(__file__), "grids/") + point out.creator.screen_name + '.png'
                                print("Trying to answer...")
                                # Reply with the message after formatting to incorporate username and the media
                                api.update_status_with_media(message.format(point out.creator.screen_name), media, in_reply_to_status_id=point out.id_str)
                                print("Efficiently replied :)")
                            # Error dealing with. for now it simply prints the error.
                            besides Exception as exc:
                                print(exc)
                        # If the tweet comprises further phrases along with our command
                        case different:
                            strive:
                                print('tweet comprises different phrases')
                                # Reply with the grid_unknown message
                                api.update_status(grid_unknown.format(point out.creator.screen_name), in_reply_to_status_id=point out.id_str)
                                print("Efficiently replied with explaination :)")
                            besides Exception as exc:
                                print(exc)
        # Sleep for two minutes
        time.sleep(120)

if __name__ == "__main__":
    print('The mighty Machineation is beginning...')
    grid_tweet()
Enter fullscreen mode

Exit fullscreen mode

and that is it..now all it’s important to do is begin it with:
pyhton bot.py
and tweet from a distinct account to your bot saying “make grid” and it ought to reply in a few minutes with the colour grid.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments