How to make a Slack App/Bot post a code block (Python) - python

In Slack you're able to post as a user in a code block like in Stackoverflow
like so
As a posting user, you're able to do this by typing "```" it then changes your input box to one formatted for code.
I need to get my Slack App/Bot to post a Tabluate Table as a code block so the formatting stays consistent with my Python output. At the moment, my code looks like this:
client.chat_postMessage(channel="#google-analytics-test",text="```" + table)
This simply posts the table in a text format with "```" added onto the start of it.
This is what comes from the bot:
How it should look coming from the user:
Any help on this would be greatly appreciated, any alternative methods to get the Tabulate Table being posted by the bot in the right format would also be very welcomed!

You also need "```" after the table and both should be in a separate line. This should do it:
client.chat_postMessage(channel="#google-analytics-test",text="```\n" + table + "\n```")
Note the added newlines "\n".

Related

How do you split a big message in different lines in python telebot?

So hey. My previous question was not well received so I'll try to do better this time.
One of my help commands for the bot sends them a list of commands that they can do. Here's the code for the specific part of the problem:
def help_command(update, context):
update.message.reply_text("What do you need my help in?")
update.message.reply_text("/commandhelp - Know my commands")
update.message.reply_text("/helpmegetapartner - Get advice on getting a partner")
dp.add_handler(CommandHandler("jhelp", help_command))
Now, I will with time add more commands, which may not fall under the given list. But there's no way (that I know of) to send the same message but in one single one, along with line breaks. This method will bombard them with messages and make them hate me. Please help!
You can use triple quotes like that :
help_command_text = """What do you need my help in?
/commandhelp - Know my commands
/helpmegetapartner - Get advice on getting a partner
/anothercommand ...
"""
And then
update.message.reply_text(help_command_text)

transform JSON file to be usable

Long story short, i get the query from spotify api which is JSON that has data about newest albums. How do i get the specific info from that like let's say every band name or every album title. I've tried a lot of ways to get that info that i found on the internet and nothing seems to work for me and after couple of hours im kinda frustrated
JSON data is on jsfiddle
here is the request
endpoint = "https://api.spotify.com/v1/browse/new-releases"
lookup_url = f"{endpoint}"
r = requests.get(lookup_url, headers=headers)
print(r.json())
you can find the
When you make this request like the comments have mentioned you get a dictionary which you can then access the keys and values. For example if you want to get the album_type you could do the following:
print(data["albums"]["items"][0]["album_type"])
Since items contains a list you would need to get the first values 0 and then access the album_type.
Output:
single
Here is a link to the code I used with your json.
I suggest you look into how to deal with json data in python, this is a good place to start.
I copied the data from the jsfiddle link.
Now try the following code:
import ast
pyobj=ast.literal_eval(str_cop_from_src)
later you can try with keys
pyobj["albums"]["items"][0]["album_type"]
pyobj will be a python dictionary will all data.

Basics of connecting python to the web and validating user input

I'm relatively new, and I'm just at a loss as to where to start. I don't expect detailed step-by-step responses (though, of course, those are more than welcome), but any nudges in the right direction would be greatly appreciated.
I want to use the Gutenberg python library to select a text based on a user's input.
Right now I have the code:
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
text = strip_headers(load_etext(11)).strip()
where the number represents the text (in this case 11 = Alice in Wonderland).
Then I have a bunch of code about what to do with the text, but I don't think that's relevant here. (If it is let me know and I can add it).
Basically, instead of just selecting a text, I want to let the user do that. I want to ask the user for their choice of author, and if Project Gutenberg (PG) has pieces by that author, have them then select from the list of book titles (if PG doesn't have anything by that author, return some response along the lines of "sorry, don't have anything by $author_name, pick someone else." And then once the user has decided on a book, have the number corresponding to that book be entered into the code.
I just have no idea where to start in this process. I know how to handle user input, but I don't know how to take that input and search for something online using it.
Ideally, I'd be able to handle things like spelling mistakes too, but that may be down the line.
I really appreciate any help anyone has the time to give. Thanks!
The gutenberg module includes facilities for searching for a text by metadata, such as author. The example from the docs is:
from gutenberg.query import get_etexts
from gutenberg.query import get_metadata
print(get_metadata('title', 2701)) # prints frozenset([u'Moby Dick; Or, The Whale'])
print(get_metadata('author', 2701)) # prints frozenset([u'Melville, Hermann'])
print(get_etexts('title', 'Moby Dick; Or, The Whale')) # prints frozenset([2701, ...])
print(get_etexts('author', 'Melville, Hermann')) # prints frozenset([2701, ...])
It sounds as if you already know how to read a value from the user into a variable, and replacing the literal author in the above would be as simple as doing something like:
author_name = my_get_input_from_user_function()
texts = get_etexts('author', author_name)
Note the following note from the same section:
Before you use one of the gutenberg.query functions you must populate the local metadata cache. This one-off process will take quite a while to complete (18 hours on my machine) but once it is done, any subsequent calls to get_etexts or get_metadata will be very fast. If you fail to populate the cache, the calls will raise an exception.
With that in mind, I haven't tried the code I've presented in this answer because I'm still waiting for my local cache to populate.

Having trouble playing music using IPython

I have the lines of code
import IPython
IPython.display.Audio(url="http://www.1happybirthday.com/PlaySong/Anna",embed=True,autoplay=True)
And I'm not really sure what's wrong. I am using try.jupyter.org to run my code, and this is within if statements. The notebook is also taking in user inputs and printing outputs. It gives no error, but just doesn't show up/start playing. I'm not really sure what's wrong.
Any help would be appreciated. Thanks!
First you should try it without the if statement. Just the two lines you mention above. This will still not work, because your URL does point to an HTML page instead of a sound file. In your case the correct URL would be 'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3'.
The Audio object which you are creating, will only be displayed if it is the last statement in a notebook cell. See my Python intro for details. If you want to use it within an if clause, you can use IPython.display.display() like this:
url = 'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3'
if 3 < 5:
IPython.display.display(IPython.display.Audio(url=url, autoplay=True))
else:
print('Hello!')

Forwarded Email parsing in Python/Any other language?

I have some mails in txt format, that have been forwarded multiple times.
I want to extract the content/the main body of the mail. This should be at the last position in the hierarchy..right? (Someone point this out if I'm wrong).
The email module doesn't give me a way to extract the content. if I make a message object, the object doesn't have a field for the content of the body.
Any idea on how to do it? Any module that exists for the same or any any particular way you can think of except the most naive one of-course of starting from the back of the text file and looking till you find the header.
If there is an easy or straightforward way/module with any other language ( I doubt), please let me know that as well!
Any help is much appreciated!
The email module doesn't give me a way to extract the content. if I make a message object, the object doesn't have a field for the content of the body.
Of course it does. Have a look at the Python documentation and examples. In particular, look at the walk and payload methods.
Try get_payload on the parsed Message object. If there is only one message, the return type will be string, otherwise it will be a list of Message objects.
Something like this:
messages = parsed_message.get_payload()
while type(messages) <> Types.StringType:
messages = messages[-1].get_payload()

Categories