samedi 23 avril 2022

Python Twitter - Tweepy to post unique content using data from txt or JSON files

I have developed a very basic Twitter bot using Python & Tweepy. It is successfully posting a tweet to twitter and I can modify the text in this line of code: response = client.create_tweet( text='Testing' ) to make different tweets

The full code I am using for this is:

import tweepy

client = tweepy.Client(consumer_key="XXXXX",
                    consumer_secret="XXXXX",
                    access_token="XXXXX",
                    access_token_secret="XXXXX")
# Create Tweet

response = client.create_tweet(
    text='Testing'
)
print(f"https://twitter.com/user/status/{response.data['id']}")

What I am trying to figure out is how I can code a Bot to randomly read data stored in file(s) and put it altogether to formulate a readable sentence or paragraph a little bit like how a mailmerge works. Here is an example, there are 3 files or 3 values:

Value1
Check out this, View this, See this
Value 2
product, item, piece
Value 3
on our online shop, on our store, on our website

If the bot was able to read and select data at random it could pick any of the data from the files or values in any order, put them together and it would make sense as a sentence or a paragraph

After researching I see that using text or JSON files might be a possibility. I followed a JSON tutorial and recreated an example that looks like this for text and images:

[
  {
    "text": "hi",
    "image": "/image1.jpg"
  },
  {
    "text": "hello",
    "image": "/image2.jpg"
  }
]

I think I have worked out how to read the JSON file with this code:

import json
with open(r"C:\Users\Administrator\Desktop\Python\test.json") as f:
    info = json.load(f)

randomChoice = random.randrange(len(info))
print (info[randomChoice])

The thing I am really struggling with is the best way to achieve this and how then to create the code that will post the tweet formulated with the random data it has selected

This is what I have so far as I attempt to combine Tweepy and the abilty to read in data from the JSON file but I can't get it to work as I don't know how to post the data it has read in to Twitter:

import tweepy
import random 
import json
with open(r"C:\Users\Administrator\Desktop\Python\test.json") as f:
    info = json.load(f)

client = tweepy.Client(consumer_key="XXXXX",
                    consumer_secret="XXXXX",
                    access_token="XXXXX",
                    access_token_secret="XXXXX")
# Create Tweet

randomChoice = random.randrange(len(info))
print (info[randomChoice])

response = client.create_tweet(
    text='NOT SURE HOW TO CODE THIS PART SO TWEEPY POSTS RANDOMLY SELECTED DATA'
print(f"https://twitter.com/user/status/{response.data['id']}")

I am brand new to Python and Tweepy so have only a very small understanding but would really appreciate any help on it




Aucun commentaire:

Enregistrer un commentaire