why aren't my slack client rtm messages showing in slack - python

Hi I'm a using the python slack client library and I cannot work out why my messages are not showing up when using the
from slackclient import SlackClient
token = 'XXXXXXXX' # my token
sc = SlackClient(token)
if sc.rtm_connect(): # connect to a Slack RTM websocket
sc.rtm_send_message('general', 'I need coffee')
else:
print('Connection Failed, invalid token?')
My Bot is part of the public channel I am trying to send the message too, I don't receive any errors but nothing is showing up in the channel I'm sending it too. I have tried both the channel name and its id.
The following does work
import json
from slackclient import SlackClient
def list_channels():
channels_call = slack_client.api_call("channels.list")
if channels_call.get('ok'):
return channels_call['channels']
return None
def send_message(channel_id, message):
slack_client.api_call(
"chat.postMessage",
channel=channel_id,
text=message,
username='mybot',
icon_emoji=':robot_face:'
)
slack_client = SlackClient('XXXXXXXXX')
channels = list_channels()
if channels:
for c in channels:
if c['name'] == 'general':
send_message(c['id'], 'I need coffee.')
else:
print("Unable to authenticate.")
And I see the message come up almost instantly in my channel.
I have confirmed through both the slack website and the api that my bot is a member of this channel.
Am I missing something about the way this works?

I think you should use your bot token instead of your user token. There 2 types of token in slack and if you want the bot to reply to the slack channel you should use bot token.

Related

Telegram Bot Api / Python: Trying to send voice message via my telegram bot

so im playing a little bit around with my telegram bot, now im already able to send normal messages and pictures. But now i want to be able to send pre recorded voice messages as an answer. In the documentation it says to use send_voice for this matter and it recommends using the file_id of a file thats already on the telegram servers. So thats what i did i send a voice message to the #RawDataBot and he returned to me the file_id of the voice message.
Problem is: When i try to trigger it i get the following error: telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: wrong file identifier/HTTP URL specified
Any ideas here on what i might be doing wrong? Here is the relevant code:
import telebot
API_KEY = <MY_API_KEY>
bot = telebot.TeleBot(API_KEY)
#start
#bot.message_handler(commands=['start'])
def start (message):
bot.send_message(message.chat.id,Textstart)
#bot.message_handler(commands=['pic'])
def start (photo):
bot.send_photo(photo.chat.id, "https://de.wikipedia.org/wiki/Zeus#/media/Datei:Zeus_Otricoli_Pio-Clementino_Inv257.jpg")
#here is the part where he is supposed to send the voice message if someone types in /audio
#bot.message_handler(commands=['audio'])
def start (voice):
bot.send_voice(voice.chat.id,"AwACAgIAAxkBAAEWjl5i5bjyudWAM9IISKWhE1Gjs5ntQgACLx8AApcNKEv97pVasPhBoCkE",)
bot.polling()
There are multiple reasons, but I think it is because of these:
file_id is unique for each individual bot and can't be transferred from one bot to another.
file_id uniquely identifies a file, but a file can have different valid file_ids even for the same bot.
See here.

Can't respond to messages in message request in fbchat

I'm trying to make a bot so that when someone sends it a message the bot sends back a joke but I've noticed this only works with people in my friends list but if random people sent to the bot then their message gets stuck in message request on messenger and even the fbchat library recognizes this and tells me in the console that there is a new pending message so is there a way to respond to those too?
Here is my code:
from fbchat import Client,ThreadLocation
class JokesBot(Client):
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
self.moveThread(ThreadLocation.PENDING,thread_id,thread_type)
self.markAsDelivered(thread_id, message_object.uid)
self.markAsRead(thread_id)
# If you're not the author, echo
if author_id != self.uid:
self.send(Message(text='wiso tefl hehe'), thread_id=thread_id, thread_type=thread_type)
client = JokesBot('email', 'password')
client.listen()
Bare in mind I still didn't implement the jokes so it's missing from the code
Thanks in advance
onMessage event called only when connected facebook friend sends you a message.
for unconnected facebook users(not friends) you should use another event onPendingMessage but unlike onMessage' in pending message things are getting more complex:
take a look at fbchat documentation
after the event called you should call the method: "fetchThreadList" in oreder to see the incoming message

Send result query Oracle to telegram bot in python

Folks,
Does anyone have any examples of executing an oracle query and sending the message via telegram bot in python?
I can only answer half of your question, which is sending the message via telegram bot in python.
Creating your bot
On Telegram, search # BotFather, send him a “/start” message
Send another “/newbot” message, then follow the instructions to setup a name and a username
Your bot is now ready, be sure to save a backup of your API token, and correct, this API token is your bot_token
Getting your Chat id
On Telegram, search your bot (by the username you just created), press the “Start” button or send a “/start” message
Open a new tab with your browser, enter https://api.telegram.org/bot/getUpdates , replace with your API token, press enter and you should see something like this:
{"ok":true,"result":[{"update_id":77xxxxxxx,
"message":{"message_id":550,"from":{"id":34xxxxxxx,"is_bot":false,"first_name":"Man Hay","last_name":"Hong","username":"manhay212","language_code":"en-HK"}
Look for “id”, for instance, 34xxxxxxx above is my chat id. Look for yours and put it as your bot_chatID in the code above
Python Code:
import requests
def telegram_bot_sendtext(bot_message):
bot_token = '<INSERT_API_KEY>'
bot_chatID = '<INSERT_CHATID>'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message
response = requests.get(send_text)
return response.json()
test = telegram_bot_sendtext("Testing Telegram bot")
print(test)

How to use telegram webhook on google cloud functions?

I have set up a telegram bot using webhooks in python on google cloud functions. Based on some sample code from the internet I got it to work as a simple echo-bot however the structure is very different to the bots I coded before using long polling:
# main.py
import os
import telegram
def webhook(request):
bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"])
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
# Reply with the same message
bot.sendMessage(chat_id=chat_id, text=update.message.text)
return "ok"
I do not understand how to add any more handlers or different functions to this, especially because cloud functions needs me to name only one function to run from the script (in this case the webhook function).
How can I convert the above logic to the one I am more familiar with below:
import os
TOKEN = "TOKEN"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(TOKEN)
# add example handler
def start(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text="Hello, I am dice bot and I will roll some tasty dice for you.")
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
# start webhook polling
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://<appname>.herokuapp.com/" + TOKEN)
updater.idle()
This code has the same structure as long polling so I know how to add additional handlers. However it has two problems:
It is the code snippet from the documentation for heroku, so I do not know whether this works the same for google cloud functions
This does not produce one function I can call in cloud functions, I tried wrapping all my code above in one big function webhook and simply running that but it does not work (and does not produce an error on my google dashboard).
Any help is appreciated!
I found this github telebot repo from yukuku with the setup of a telegram bot on App Engine and the webhook implementation using python. As mentioned before you may want to use App Engine in order to implement your bot with many functions on the same main.py file.
I just tried and it's working for me.
i did that here's my snippet
from telegram import Bot,Update
from telegram.ext import CommandHandler,Dispatcher
import os
TOKEN = os.getenv('TOKEN')
bot = Bot(token=TOKEN)
dispatcher = Dispatcher(bot,None,workers=0)
def start(update,context):
context.bot.send_message(chat_id=update.effective_chat.id,text="I am a bot, you can talk to me")
dispatcher.add_handler(CommandHandler('start',start))
def main(request):
update = Update.de_json(request.get_json(force=True), bot)
dispatcher.process_update(update)
return "OK"
# below function to be used only once to set webhook url on telegram
def set_webhook(request):
global bot
global TOKEN
s = bot.setWebhook(f"{URL}/{TOKEN}") # replace your functions URL,TOKEN
if s:
return "Webhook Setup OK"
else:
return "Webhook Setup Failed"

How to get user info with bot token

I am using python slack client to connect and send messages with a bot application.
slc = SlackClient("BOT_USER_TOKEN")
out = slc.api_call(method='users.profile.get', user='XXX')
I am getting not_allowed_token_type error in output json. I am able to call:
slc.api_call(method='chat.PostMessage',channel)
Is there a way to get user email, name from slack API. previously I got the username from event messages. but now I am getting only user id so I am looking for a solution to fetch user info using that id.
The reason you get this error message is that users.profile.get does not work with bot tokens.
To mitigate just use the user token that you received along with your bot token when installing your Slack app.

Categories

Resources