🛠Generate Word Search and Post to Twitter using Python and Node.js
2025-04-03
Generate Word Search and Post to Twitter using Python and Node.js
Prerequisites
Ensure you have the following installed:
- Python 3
- Node.js
- Required dependencies
Step 1: Generate a Word Search Puzzle PDF
We will use the word-search-generator
package to create a word search puzzle in PDF format.
Install the required package:
python3 -m pip install word-search-generator --break-system-packages
Generate the Word Search PDF in generate_wordsearch.py
from word_search_generator import WordSearch puzzle = WordSearch(level=3) words = puzzle.random_words(10, secret=False, reset_size=True) images = convert_from_path("wordsearch.pdf") puzzle.save(path="./wordsearch.pdf")
Step 2: Convert PDF to PNG
We will use pdf2image
to convert the PDF to an image.
Install the required package & dependence package:
python3 -m pip install pdf2image --break-system-packages brew install poppler
Convert PDF to PNG
from pdf2image import convert_from_path images = convert_from_path("wordsearch.pdf") images[0].save("wordsearch.png", "PNG")
Step 3: Run python using Node.js
const runPythonScript = () => { return new Promise((resolve, reject) => { const pythonProcess = spawn("python3", ["generate_wordsearch.py"]); let data = ""; pythonProcess.stdout.on("data", (chunk) => { data += chunk.toString(); }); pythonProcess.stderr.on("data", (error) => { console.error("Error:", error.toString()); reject(error.toString()); }); pythonProcess.on("close", (code) => { if (code === 0) { resolve(data); } else { reject(`Python script exited with code ${code}`); } }); }); };
Step 4: Post the Image to Twitter using Node.js
We will use twitter-api-v2
to post the image to Twitter.
Install the required package:
npm install twitter-api-v2
Post Image to Twitter
import { TwitterApi } from 'twitter-api-v2'; import fs from 'fs'; const client = new TwitterApi({ appKey: 'YOUR_APP_KEY', appSecret: 'YOUR_APP_SECRET', accessToken: 'YOUR_ACCESS_TOKEN', accessSecret: 'YOUR_ACCESS_SECRET' }); async function postImage() { const imageData = fs.readFileSync('wordsearch.png'); const mediaId = await client.v1.uploadMedia(imageData, { type: 'png' }); await client.v1.tweet('Here is your Word Search Puzzle!', { media_ids: mediaId }); } runPythonScript() .then((resultWS) => { postImage(); }) .catch((err) => console.error("Error:", err));
Conclusion
This guide demonstrates how to generate a word search puzzle, convert it to an image, and post it to Twitter using Python and Node.js. Adjust the words in the puzzle and customize the Twitter post as needed!