I am trying to create a Discord bot that will monitor my twitter feed and post messages into a specific channel on my Discord server. I know solutions already exist for this task (zapier and IFTTT) but I am also wanting to use this as an exercise to develop my coding skills.
I have been following this example but now I haven't been able to get this to run successfully. My problem is that the bot can successfully join the Discord server and monitor my twitter feed but it won't post the message. I have used a print statement (that print(message) line) to determine that the bot does receive new tweets.
I have stored my access tokens and secret keys in another file called twitter_credentials.py (hence that import). I'm using the Tweepy and discord.py libraries, any help will be greatly appreciated - The code below uses << redacted >> identifying strings:
import tweepy, discord
import twitter_credentials
twitter_access_token = twitter_credentials.access_token
twitter_access_token_secret = twitter_credentials.access_token_secret
twitter_consumer_key = twitter_credentials.consumer_key
twitter_consumer_secret = twitter_credentials.consumer_secret
discord_token = twitter_credentials.token_twitter_bot
client = discord.Client()
class StdOutListener(tweepy.StreamListener):
""" A listener handles tweets that are received from the stream.
This is a basic listener that just prints received tweets to stdout."""
def on_status(self, status):
if not status.in_reply_to_status_id == None:
message = '#{0} : {1}'.format(status.in_reply_to_screen_name, status.text)
else:
message = '{0}'.format(status.text)
print(message)
channel = client.get_channel('<<channel_id>>')
em = discord.Embed(title='Tweet', description='My Twitter Feed', colour=0xDEADBF)
em.set_author(name='# <<Twitter_handle>>', icon_url=client.user.default_avatar_url)
client.send_message(channel, message, embed = em)
#client.event
async def on_ready():
if not client.is_logged_in:
raise Exception('Unable to connect to Discord')
else:
print('Connected to Discord')
auth = tweepy.OAuthHandler(twitter_consumer_key, twitter_consumer_secret, callback = 'oob')
auth.secure = True
auth.set_access_token(twitter_access_token, twitter_access_token_secret)
print('Starting Twitter stream')
stream = tweepy.Stream(auth, StdOutListener())
stream.filter(['<<twitter_ID>>'])
client.run(discord_token)
Thanks
Qui
Related
I have been using the Telegram API for a while to listen for messages in specific channels on one account. The code below works ok. I tried to use the same code to create another listener for a different account but it doesn't work. I don't get any errors.
When I look on the official Telegram app the listener is not listed under "Devices" which suggests it is not connecting to the API correctly.
Before testing I created a new API ID and hash at my.telegram.org. I've triple checked that the ID, hash and channel ID are all correct.
Can anyone think what the issue might be?
Thanks
from telethon import TelegramClient, events, sync
api_id = 'xxxxxxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxx'
client = TelegramClient('anon', api_id, api_hash)
chat_id = xxxxxxxx
#client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
new_message = event.message.message
chat_id = event.chat_id
print(chat_id)
print(new_message)
print()
screenshot = "new_image.jpg"
if event.message.photo:
await event.download_media(screenshot)
print("New image received")
#client.on(events.NewMessage(chats=[chat_id]))
chats=[] - here must be a python list,
like chats=[-123456789]
I'm trying to build a discord bot that sends new twitter posts into chat (in realtime). Not all that familiar to async yet, and with minimal examples available I'm still kind of lost.
I have two classes, twitterClient and discordClient, and I pass the message sending function and the event loop to the twitterClient. I then call asyncio.run_coroutine_threadsafe to run the message sending function when the twitterClient receives a tweet.
When I run this and post a tweet, the program seems to receive the tweet (as shown by the print statement) but the program doesn't get any further. Since ctrl-c doesn't work after this step, it seems to me that the program freezes there. What should I do? Am I even using asyncio correctly?
import discord
from discord.ext import commands
import tweepy
import asyncio
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
BEARER = os.getenv('TWITTER_BEARER_TOKEN')
rule = {'fromknowgnod':'from:knowgnod'}
class twitterClient(tweepy.StreamingClient):
def __init__(self, send, loop, *args, **kwargs):
super().__init__(*args, **kwargs)
self.loop = loop
self.send = send
def on_connect(self):
print('connected to stream')
# check if rule already uploaded
api_rule_tags = [i.tag for i in self.get_rules().data]
if list(rule.keys())[0] not in api_rule_tags:
self.add_rule(value=rule[list(rule.keys())[0]], tag=list(rule.keys())[0])
def on_tweet(self, tweet):
print("received tweet: "+str(tweet.id))
a = asyncio.run_coroutine_threadsafe(self.send(tweet.id), self.loop)
a.result()
def on_errors(self, errors):
print(f"Received error code {errors}")
self.disconnect()
return False
class discordClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
myStream = twitterClient(self.send_message, asyncio.get_event_loop(), BEARER)
myStream.filter()
async def send_message(self, msg):
c = self.get_channel(1003516355003289694)
c.send(f'https://twitter.com/knowgnod/status/{msg}')
intents = discord.Intents.default()
intents.messages = True
client = discordClient(intents=intents)
client.run(TOKEN)
I want to create a bot to post my texts to a channel...
Can anyone help me with the code?
this is the code that I tried :
import telegram
token = "5002307835:AAGOu4f******************"
chat_id = "1382******"
bot = telegram.Bot(token)
def send_message(message):
return bot.send_message(chat_id,message)
send_message("HI")
but i got this error : telegram.error.BadRequest: Chat not found
also i tried : chat_id = "-1382******" and chat_id = -1382****** and chat_id = 1382******
use it without " "
e.g.
import telegram
chat_id = 1382******
token = "TOKEN"
if not work, try it with - and no "", it will works!
e.g.
import telegram
chat_id = -1382******
token = "TOKEN"
Channels ids usually starts with -100, so
chat_id = -1001382******
Put it as integer
You can also get the channel id sending a message in the channel as normal user and handling it with the bot. In message.chat.id you will see the correct id
Or just forward a channel message to the bot https://t.me/nguLikJSONbot
First of all, you should be administrator of a channel and then send message to it.
For send text, file or photo with caption to a specific user, the target user should be member of your bot and then change chat_id to user id in telegram.
import telegram
token = "5002307835:AAGOu4f******************"
# "#{0}".format("botfather") ==> #botfather
chat_id = "#{0}".format("your_channel_name")
# For sending message to a specific user
# chat_id = 18558...
bot = telegram.Bot(token)
def send_message(message):
return bot.send_message(chat_id, message)
your_msg = "Hello"
send_message(your_msg)
My goal is to create a Telegram listener on a specific channel that copies new messages and posts them as tweets on Twitter. So far the python I wrote works well when I run it on my computer, when I send a mock message on my Telegram channel, it detects that a message has been sent, goes down the code, and a tweet is created with the text.
However, this is not the case when I try to run in on an AWS instance (ubuntu).
when running the following code:
import tweepy
from telethon import TelegramClient, events
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
api = tweepy.API(auth)
print("start")
# Listen to new messages on Telegram Channel
bot = TelegramClient("bot", api_id, api_hash).start(bot_token=bot_token)
with bot:
print("bot-start")
#client.on(events.NewMessage(chats=ChannelURL))
async def newmessagelistener(event):
print("action detected")
client.start()
client.run_until_disconnected()
Things start out ok at the beginning, but then when I write a new test message on the telegram channel - nothing, no "action detected" is returned, only "start" and "bot-start", no tweet is posted.
Any ideas as to what's going on?
Thanks in advance!
I have this code
from telethon.sync import TelegramClient, events
with TelegramClient('name', api_id, api_hash) as client:
#client.on(events.NewMessage(pattern=pattern))
async def handler(event):
await event.reply("Here should be the Chat or Group name")
How to implement this?
if we are talking only about groups/channels
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = chat_from.title
Else (If we want to get the full name of chat entities, including Users):
from telethon import utils
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = utils.get_display_name(chat_from)
get_display_name() actually gets a name that you would see. Works for types User, Channel, Chat
That method shall not have await