slack python api delete message - python

I am trying to use my bot to delete certain messages in a slack channel with this api call
import os
import time
import re
from slackclient import SlackClient
slack_client = SlackClient(
'xsssssseeeeeeee')
slack_mute_bot_id = None
def delete_message(slack_event):
for event in slack_event:
if event["type"] == "message":
message_text = event['text']
time_stamp = event['ts']
channel_id = event['channel']
slack_client.api_call(
'chat.delete',
channel=channel_id,
ts=time_stamp,
as_user=True
)
print(message_text + " delted")
if __name__ == "__main__":
if slack_client.rtm_connect(with_team_state=False):
slack_mute_bot_id = slack_client.api_call("auth.test")["user_id"]
while True:
# print(slack_client.rtm_read())
delete_message(slack_client.rtm_read())
time.sleep(1)
else:
print("Connection failed. Exception traceback printed above.")
I do not get any error message after doing this and the bot does not delete the message. I am using the bot user token. I have benn able to send message succesfully but the delete method does not work and still gives np responses

Refer - https://api.slack.com/methods/chat.delete
When used with a user token, this method may only delete messages
that user themselves can delete in Slack.
When used with a bot token, this method may delete only messages
posted by that bot.
I got stumbled into the same thing.

Related

DeepAI API error - {"err": "error processing given inputs from request"}

I'm a noobie at Python and was just messing around, but now I'm really curious why it isn't working. I'm currently trying to build a telegram bot that generates an image based on the text given to the bot. I think there might be a problem with my DeepAI api? When I click this link: https://api.deepai.org/api/text2img i always get the error
{"err": "error processing given inputs from request"}
. The bot is linked but gives me the error as in the code below. My code below:
import requests
import json
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
def text_to_image(update, context):
# Get the text from the user
text = update.message.text
# Set up the DeepAI API request
api_key = "{{ api }}"
headers = {
"api-key": api_key
}
data = {
"text": text
}
# Make the request to the DeepAI API
response = requests.post("https://api.deepai.org/api/text2img", headers=headers, json=data)
if response.status_code != 200:
update.message.reply_text("An error occurred while generating the image. Please try again later.")
return
# Get the generated image from the response
response_json = response.json()
image_url = response_json["output_url"]
# Send the generated image to the user
context.bot.send_photo(chat_id=update.effective_chat.id, photo=image_url)
def main():
# Set up the Telegram bot
updater = Updater(token="{{ api }}", use_context=True)
dispatcher = updater.dispatcher
# Add the text_to_image handler
text_to_image_handler = MessageHandler(Filters.text, text_to_image)
dispatcher.add_handler(text_to_image_handler)
# Start the bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
I've tried changing code and different things but nothing seems to work, i'm really stuck right now
From the looks of it, it's an error on the API side of things. The status code of the API server depends on traffic and account/key.
Things to do:
Check if your API key is valid and wait when server works on google, then try to run your code

Slack app.message is reacting toold messages

Im trying to create a slack bot with slack_bolt package that is searching if there are matches in slack history in the channel on a new message. For some reason app.message is triggered on messages that have been sent before the app was running. Is this preventable or do i have to handle this case? It would be to best to prevent it since if i want to use this on a channel with a big history that might cause some problems. I don't want it to check all the X thousand messages in the history.
wanted result:
ME: Hi!
-- starting slack app --
ME: Hi!
SlackBOT in thread: A similar message has been posted: (link to first massage)
result:
ME: Hi!
SlackBOT in thread: A similar message has been posted (link to itself) (this only arrives after the slackbot message to the second Hi)
-- starting slack app --
ME: Hi!
SlackBOT in thread: A similar message has been posted (with link to first message)
import os
import json
import ssl
import certifi
from slack_bolt import App
from slack_sdk.web import WebClient
from slack_bolt.adapter.socket_mode import SocketModeHandler
from utils import get_list_of_same_message_indexes, get_ts_of_message_for_link
history_limit = 50
ssl_context = ssl.create_default_context(cafile=certifi.where())
slack_client = WebClient(token=os.environ['BOT_TOKEN'], ssl=ssl_context)
app = App(client=slack_client)
#app.message(".*")
def check_history(message, say):
# say() sends a message to the channel where the event was triggered
history = app.client.conversations_history(channel=slack_channel_ID,limit=history_limit).get("messages")
#if the message is not comming from a thread
print(message.get("text"))
if not message.get("thread_ts"):
print("new message")
thread= message.get("ts")
list_of_same_messages = get_list_of_same_message_indexes(message,history)
if len(list_of_same_messages) > 0:
print(list_of_same_messages)
example_ts = get_ts_of_message_for_link(history[list_of_same_messages[0]])
print(example_ts)
#channel = history[list_of_same_messages[0]].get("channel")
message_text = f"A similar message has been posted: https://test-dev.slack.com/archives/{slack_channel_ID}/p{example_ts}"
say({"text": message_text,"thread_ts": thread})
else:
print("Nothing")
if __name__ == "__main__":
SocketModeHandler(app, os.environ["APP_TOKEN"]).start()

How to get the message id telegram channel from my bot and remove that message?

hi and thanks for your answer. i want to create a bot for forward message to my channel and delete the last message every 1 minute
i made that but i have some problem for removing the last message. i cant get the last message id from my channel to the bot.
my source is:
from telegram.bot import Bot
from telegram.update import Update
from telegram.ext.updater import Updater
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters
from telegram.chataction import ChatAction
from time import sleep
import telegram_send
import socket
import telegram
import json
api_key="My API Key"
user_id = "My User Id"
updater = Updater(api_key, use_context=True)
bot = telegram.Bot(token=api_key)
def echo(update: Update, context: CallbackContext):
context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
sleep(60)
if update.message['photo'] == []:
bot.send_message(chat_id=user_id, text=update.message.text)
else:
fileID = update.message['photo'][-1]['file_id']
context.bot.sendPhoto(chat_id = user_id,caption=update.message['caption'],photo = fileID)
msg_id = update.message._id_attrs[]
#------------- And Also i user that too -------------
#msg_id=update.message.message_id
#------------- -------------
context.bot.delete_message(chat_id=user_id, message_id=msg_id)
update.effective_chat
update.effective_user
update.effective_message
print(json.dumps(update.to_dict(), indent=2))
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.document | Filters.photo, echo))
dp.add_handler(MessageHandler(Filters.text, echo))
updater.start_polling()
and when i use that code this error will show:
The message_id that you want to remove is not exist....
actually i type a message id in manually for delete message and it was work
but i want to delete that message auto
please help me to do that. thanks
I fixed That With Python-Telegram-Bot Version 20
Read This Docs:
https://docs.python-telegram-bot.org/en/v20.0a2/

Creating Slackbot with Google Sheets integration using python and git

My name is Ken. I am trying to create a Slack Bot first one message every Monday at 9:00 am and asks for a input (goal number of sales for the week). Then responds with user input in new message saying (great your weekly sales goal is (#). Then it takes this number and adds it to Google sheets. Then asks user to enter daily goal for the day. And responds with (daily goal set as). Then at 9:00 pm asks user to input the number of deals written and keeps track of all data in Google sheets and provides graphs. I have been thinking maybe MySQL would work for that too.
Here is some of the code I have so far:
starterbot.py
import os
import time
from slackclient import slackclient
# starterbot's ID as an environment variable
BOT_ID = os.environ.get("BOT_ID")
# contasts
AT_BOT = "<#" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"
#instantiate Slack & Twilio clients
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
def handle_command (command, channel)
"""
Receives commnds directed at the bot and determines if they
are valid commands. if so, then acts on the commands. if not,
returns back what it needs for clarification.
"""
response = "Not sure what you mean. Use the *" + EXAMPLE_COMMAND + \
"* command with numbers, delimited by spaces."
if command.startswitch(EXAMPLE_COMMAND):
response = "Sure ... wire some more c ie then I can do
that!"
slack_client.api_call("chat.postMessage", channel=channel,
text=response, as_user=True)
def parse_slack_output(slack_messages):
"""
The Slack Real Time Messaging API is an event firehose.
this parsing function returns None unless a message is
directed at the Bot, based on its ID.
"""
if slack_messages and len(slack_messages) > 0;
for message in slack_messages:
if message and 'text' in message and AT_BOT in message['text']:
command = message['text'].split(AT_BOT)[1].strip().lower()
channel = message['channel']
# return text after the # mention, white space removed
return command, channel
return None, None
if __name__ == "__main__":
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
if slack_client.rtm_connect():
print("starterbot connected and running!")
while True:
command, channel = parse_slack_output(slack_client.rtm_read())
if command and channel:
handle_command(command, channel)
time.sleep(READ_WEBSOCKET_DELAY)
else:
print("Connection failed. Invalid Slack token or bot ID?")
bot_id_py
import os
from slackclient import SlackClient
import pdb
BOT_NAME = 'pilot4u'
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
if __name__ == "__main__":
api_call = slack_client.api_call("users.list")
if api_call.get('members'):
pdb.set_trace()
# Retrieve all users so we can find our bot
users = api_call.get('members')
for user in users:
if 'name' in user and user.get('name') == BOT_NAME:
print("Bot ID for '" + user ['name'] + "'is " +
user.get('id'))
else:
print("could not find bot user with the name " + BOT_NAME)

Find channel name of message with SlackClient

I am trying to print the channel a message was posted to in slack with the python SlackClient. After running this code I only get an ID and not the channel name.
import time
import os
from slackclient import SlackClient
BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')
def main():
# Creates a slackclient instance with bots token
sc = SlackClient(BOT_TOKEN)
#Connect to slack
if sc.rtm_connect():
print "connected"
while True:
# Read latest messages
for slack_message in sc.rtm_read():
message = slack_message.get("text")
print message
channel = slack_message.get("channel")
print channels
time.sleep(1)
if __name__ == '__main__':
main()
This is the output:
test
U1K78788H
This will always produce a channel id and not channel name. You must call channels.info to get the channel name.
import time
import os
from slackclient import SlackClient
BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')
def main():
# Creates a slackclient instance with bots token
sc = SlackClient(BOT_TOKEN)
#Connect to slack
if sc.rtm_connect():
print "connected"
while True:
# Read latest messages
for slack_message in sc.rtm_read():
message = slack_message.get("text")
print message
channel = slack_message.get("channel")
print channel
channel_info=sc.api_call("channels.info",channel=channel)
print channel_info["channel"]["name"]
time.sleep(1)
if __name__ == '__main__':
main()
This will also print channel Name.
Another way is that you can store names of all the channels with their channel_id in a dictionary beforehand. And then get the channel name with id as key.
I'm not sure what you are outputting. Shouldn't "channels" be "channel" ? Also, I think this output is the "user" field. The "Channel" field should yield an id starting with C or G (doc).
{
"type": "message",
"channel": "C2147483705",
"user": "U2147483697",
"text": "Hello world",
"ts": "1355517523.000005"
}
Then, use either the python client to retrieve the channel name, if it stores it (I don't know the Python client), or use the web API method channels.info to retrieve the channel name.

Categories

Resources