Skip to content

Instantly share code, notes, and snippets.

@Matros777
Last active October 8, 2024 10:44
Show Gist options
  • Save Matros777/764f655260749126364325e03815e565 to your computer and use it in GitHub Desktop.
Save Matros777/764f655260749126364325e03815e565 to your computer and use it in GitHub Desktop.
How to Publish Tweets from Telegram
import tweepy
import telebot
import logging
import os
# Twitter API keys (keep your actual keys safe)
api_key = "YOUR_TWITTER_API_KEY"
api_secret_key = "YOUR_TWITTER_API_SECRET_KEY"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"
# OAuth1.1 Authentication for media upload in Twitter
auth = tweepy.OAuth1UserHandler(api_key, api_secret_key, access_token, access_token_secret)
api_v1 = tweepy.API(auth)
# OAuth2 Authentication for publishing tweets via v2 API
client = tweepy.Client(consumer_key=api_key, consumer_secret=api_secret_key,
access_token=access_token, access_token_secret=access_token_secret)
# Telegram Bot Token (from BotFather)
telegram_token = "YOUR_TELEGRAM_BOT_TOKEN"
bot = telebot.TeleBot(telegram_token)
# Store user data for tweets
user_data = {}
# Set allowed chat ID (replace with your actual chat ID)
allowed_chat_id = YOUR_ALLOWED_CHAT_ID
# Enable logging for debugging
logging.basicConfig(level=logging.INFO)
# Welcome Message
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, "Welcome! 👋\n\nTo publish a post on Twitter, first send the text (up to 280 characters). Then send an image.\n\nExample:\n1. 'This is my tweet text!'\n2. Send an image.")
# Text Message Handler
@bot.message_handler(func=lambda message: message.chat.id == allowed_chat_id and len(message.text) <= 280)
def get_text(message):
user_data[message.from_user.id] = {'text': message.text}
bot.send_message(message.chat.id, f"Text received: '{message.text}'\nNow please send an image.")
@bot.message_handler(func=lambda message: message.chat.id == allowed_chat_id and len(message.text) > 280)
def too_long_text(message):
bot.send_message(message.chat.id, "The text is too long! Please make sure it is within 280 characters.")
# Handle Image Uploads
@bot.message_handler(content_types=['photo'])
def get_image(message):
user_id = message.from_user.id
if user_id not in user_data or 'text' not in user_data[user_id]:
bot.send_message(message.chat.id, "Please send the text for the post first.")
return
# Download the image
photo = message.photo[-1]
image_path = f"temp_image_{user_id}.jpg"
file_info = bot.get_file(photo.file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(image_path, 'wb') as new_file:
new_file.write(downloaded_file)
# Upload the image to Twitter
try:
media = api_v1.media_upload(image_path)
tweet_text = user_data[user_id]['text']
response = client.create_tweet(text=tweet_text, media_ids=[media.media_id])
bot.send_message(message.chat.id, f"Tweet created successfully!\n\n{tweet_text}")
logging.info(f"Tweet created successfully with ID: {response.data['id']}")
# Delete temporary image file
os.remove(image_path)
except Exception as e:
logging.error(f"An error occurred while tweeting: {e}")
bot.send_message(message.chat.id, "An error occurred while publishing the tweet. Please try again.")
# Run the Telegram Bot
if __name__ == "__main__":
bot.infinity_polling()
@Matros777
Copy link
Author

Here’s a comprehensive guide for your GitHub Gist on setting up the Telegram-to-Twitter bot, including instructions for installing necessary libraries and obtaining the required API keys:

Telegram-to-Twitter Bot: Setup Instructions

This guide will help you set up a Telegram-to-Twitter bot using Python. You will learn how to install necessary libraries, obtain API keys, and run the bot.

Prerequisites

Step 1: Install Required Libraries

You will need to install the following libraries:

  • Tweepy: A library for accessing the Twitter API.
  • Telebot: A library for creating Telegram bots.

To install these libraries, open your terminal or command prompt and run:

bash
pip install tweepy pyTelegramBotAPI

Step 2: Obtain API Keys

Twitter API Keys

  1. Create a Twitter Developer Account:

  2. Create a Twitter App:

    • Once your account is approved, navigate to the Projects & Apps section and create a new app.
  3. Generate Keys and Tokens:

    • In your app's settings, you will find your:
      • API Key
      • API Secret Key
      • Access Token
      • Access Token Secret

Telegram Bot Token

  1. Create a Telegram Bot:
    • Open Telegram and search for BotFather.
    • Start a chat with BotFather and send the command /newbot.
    • Follow the prompts to create a new bot. You will receive a Telegram Bot Token after creation.

Allowed Chat ID

  • Determine the Chat ID where the bot will operate (e.g., your personal chat or a group chat). You can find your chat ID by sending a message to the bot and checking the logs or using the following command in a chat with your bot:

python
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, f"Your chat ID is: {message.chat.id}")

Step 3: Update the Code

Replace the placeholders in the code with your actual keys and chat ID:

python
import tweepy
import telebot
import logging
import os

Twitter API keys (keep your actual keys safe)

api_key = "YOUR_TWITTER_API_KEY"
api_secret_key = "YOUR_TWITTER_API_SECRET_KEY"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"

Telegram Bot Token (from BotFather)

telegram_token = "YOUR_TELEGRAM_BOT_TOKEN"

Set allowed chat ID (replace with your actual chat ID)

allowed_chat_id = YOUR_ALLOWED_CHAT_ID # e.g., 123456789

Step 4: Run the Script

  1. Save your complete code in a Python file (e.g., telegram_to_twitter_bot.py).
  2. Open a terminal or command prompt in the directory where your script is located.
  3. Run the script using:

bash
python telegram_to_twitter_bot.py

Step 5: Interact with the Bot

  • Open Telegram and start a chat with your bot.
  • Send the /start command, and follow the prompts to publish tweets with text and images.

Note

Ensure you handle your API keys and tokens securely and avoid sharing them in public repositories. Store sensitive information in environment variables or a configuration file if possible.

By following these instructions, you should be able to set up your Telegram-to-Twitter bot successfully! Feel free to customize and expand its functionality as needed.

@Matros777
Copy link
Author

Using a .env file to store sensitive information like API keys is a popular practice in Python projects. This method allows you to keep your configuration separate from your code, making it easier to manage and secure. Here’s how you can use a .env file in your project:

Step 1: Create a .env File

  1. Create a file named .env in the root directory of your project.

  2. Add your sensitive information in the following format:

    API_KEY=your_api_key_here
    API_SECRET=your_api_secret_here
    ACCESS_TOKEN=your_access_token_here
    ACCESS_TOKEN_SECRET=your_access_token_secret_here
    TELEGRAM_TOKEN=your_telegram_token_here
    ALLOWED_CHAT_ID=your_allowed_chat_id_here

Step 2: Install python-dotenv

To read the .env file in your Python code, you’ll need the python-dotenv library. Install it using pip:

pip install python-dotenv

Step 3: Load the .env File in Your Code

Now you can use the python-dotenv library to load the environment variables from your .env file. Here’s an example of how to do this:

import os
from dotenv import load_dotenv

# Load environment variables from the .env file
load_dotenv()

# Access the API keys and tokens
api_key = os.getenv("API_KEY")
api_secret_key = os.getenv("API_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
telegram_token = os.getenv("TELEGRAM_TOKEN")
allowed_chat_id = os.getenv("ALLOWED_CHAT_ID")

# Example of using the keys in your code
print(f"API Key: {api_key}")
print(f"Telegram Token: {telegram_token}")


### Step 4: Add the `.env` File to `.gitignore`

To prevent your `.env` file from being tracked by version control (like Git), add it to your `.gitignore` file:


# .gitignore
.env


### Conclusion

Using a `.env` file helps keep your sensitive information secure and separate from your codebase. Always remember to keep your `.env` file private and never share it publicly! This method also allows for easy changes to your configuration without modifying the code, making your application more flexible and secure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment