me again, with another Python question.
I have a variable that is pieced together from a template in the config file.
This is the format that the config.ini file prepares the variable for sending:
template =#${var1} ${var2}: ${var3}
I set each of the variables in the python code as such:
templateArgs = dict()
flight = a.flight or a.hex
flight = flight.replace(" ", "")
templateArgs['var1'] = aircraftdata.plane(a.hex)
templateArgs['var2'] = aircraftdata.oper(a.hex)
templateArgs['var3'] = "%.1f" % a.distance
It is prepared for Twitter, but Im removing that part, but sending the tweet content in the email for someone to review before posting.
This is where it is combined:
tweet = Template(parser.get('tweet', 'tweet_template')).substitute(templateArgs)
Its an SMTP email thats being sent with the data, but Ive got all that part sorted, Im just trying to make it look better. Its a hashtag string for twitter, but Im only using it in an email.
SMTP Email includes like this:
<p>Tweet: """ + tweet + """</p>
Id like, and this is the question for you, how ... in the ini file can I put in a line break so that when the email comes through each of the vars come through on a new line.
Its all working perfectly, its honestly just the new line I want to introduce. All the rest is working fine.
Im perplexed, and working from someone elses code, and a bit lost.
Sorry for the long question...just trying make sure you geniuses have enough info.
Any helpers?
Cheers
Simon
Related
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".
I have a string variable in Zapier that contains multiple emails (a#gmail.com,b#gmail.com, etc.). I need to extract each email and pass it on to the next Zapier action.I've taken a screen shot of where this appears in Zapier So a string that has 2 emails would cause the next Zapier action to run twice.
I've tried parsing the string and loading a dictionary, returning the dictionary.
emails = []
attendeeList = input_data['attendeeEmails'].split()
for email in attendeeList:
a = {'Email' : email}
emails.append(a)
return emails
This returns all the emails in a form basically the same as they were submitted - comma separated list or string. (So not multiples). It does cause the next action to run in the Zap, but with multiple emails in the field "Email". Not what I want.
I've also tried just returning each email as I march through the created List.
attendeeList = input_data['attendeeEmails'].split()
for email in attendeeList:
output = {'Email' : email}
I haven't seen any output from this one yet. It's taking me about 1/2 hr to see results from any tweaks.
I'm afraid I don't know Python very well - only what I could learn from several hours spent in "Code Academy". So I know enough to be dangerous. But with the passing of variables and purported ability of Zapier to trigger multiple actions from the return of one dictionary, I'm a little overwhelmed. I'm sure it's simple if you know more than me.
My source of the string containing the emails is Google Calendar. And with the 15 min checking cycle it's a long slog to get feedback on what I've done. Any guidance would be awesome.
The following one-liner would give you a list of dictionaries from the comma-separated list of emails. Hopefully Zapier would take it from there.
[{'Email': email.strip()} for email in input_data['attendeeEmails'].split(',')]
Also please be aware you shouldn't have to wait 15 minutes every time. You can just click on re-test when you get to the 'test this step' stage.
You need to split on a delimiter, in this case a comma.
So your attendeeList would look like this:
attendeeList = input_data['attendeeEmails'].split(',')
And to remove any extra whitespace, you should then .strip() the emails in your loop like this:
for email in attendeeList:
a = {'Email' : email.strip()}
emails.append(a)
So i am currently creating a quiz program which requires a really basic authentication. This is the psuedocode that i have.
Start
Open UserCredentials.txt (This is where the user ID is stored)
Get UserID
If UserID is in UserCredetials.txt( This is the part that i could not figure out how to do)
..Passtries = 0
..While passtries != 1
....Get password
....If password is UserCredentials.txt( The other part which i couldnt do.)
......Passtries = 1 (Correct password, it will exit the loop)
....else
......Passtries = 0 (wrong password, it will continue looping)
....WhileEnd
So the problem here is that i could not figure out how to check the UserCredentials.txt file based on what the user has inputted and write the code for it in python. (Python 2.7.11)
Note that in the UserCredentials.txt, the userID and password are stored side by side [Izzaz abc123]
Also i am still kind off new to python, so go easy on me :)
Any help is appreciated.
.you should start to use dict for data container and xml or json for the formatting
UserCredentials.xml
members_dict:
User(Name = "izzaz", Passwort: "abc123")
User(Name = "isssz", Passwort: "asassa")
.start
.open UserCredentials.xml/json
.get members_users
.if user_id_input in members_users continue
.if user_passwort_input == members[user_id_input][passwort]:
its only a guide how it can work, more information about OrderedDict, Xml Parsing,
create simple Xml file
Apologies for the amateur question. I'm just learning Python and I'm fumbling around this XMPP bot script using XMPP.
I have a bot built using the MUC bot example from SleekXMPP: http://sleekxmpp.com/getting_started/muc.html
Where my bot differs from the example is my script creates a SQLite database and on each group_message event, parses the XML to retrieve the nick and message body text and write it to the database with a timestamp.
Here is the part of my bot that's recording the msg output from the XMPP channel:
def groupchat_message(self, msg):
if msg['type'] in ('groupchat'):
raw = str(msg) # Save raw XML as a string in the database for debugging purposes
timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
fromuser = str(msg['from']) # Convert "from" attribute to string so it can be split
author = fromuser.split('/')[1] # Split "from" attribute to remove channel address leaving only nick behind
body = msg['body']
msginsert = [timestamp, author, body, raw] # Database input list to be handed to placeholders.
db.execute("INSERT INTO messages VALUES (?,?,?,?)", msginsert) # "?" placeholder is REQUIRED for automatic database sanitization.
dbconn.commit()
print("[",timestamp,"]",author,": ",body, sep='')
else:
print(msg)
The print statements are just for debugging purposes so I can watch the messages tick by in the terminal so I know the script is running.
In the recorded information I would like to also include the user's role or affiliation in the XMPP channel so admins and moderators can be singled out. This is what I'm having trouble wrapping my head around. It seems like I should be able to do it based on the SleekXMPP stanza docs but I'm having trouble figuring out how I get from the message XML to the role/affiliation information.
How can I take the information provided in the message XML and get back the role and/or affiliation of the user who posted that message?
For reference, this is the raw XML output from the XMPP channel for messages:
<message to="username#example.com" from="channelname#channels.example.com/User Nick" id="1453" type="groupchat">
<body>This is the message body text</body>
<x xmlns="jabber:x:event">
<composing />
</x>
</message>
The role/affiliation isn't included in the message, it is part of the state of the chat.
As a reminder, XMPP has three different stanzas that get send: <message>, which you had as an example, <iq>, which are used to retrieve or set things and <presence>, which indicates the presence of things. The role/affiliation information is included in a presence stanza. For example in the first presence stanzas your client receives to inform it of who is present in the room already, see Example 21 from XEP-0045 (Multi-User Chat). Your client also receives new presence stanzas whenever someone's nickname, role or affiliation changes or when they leave the room.
You should make sure you store this information yourself, because SleekXMPP doesn't do it for you. This can be done by creating a dictionary that stores, for every nickname, their role and one for their affiliation. On presence changes you should make sure to update this information. Then you can use those dictionaries in your message handler to log their role/affiliation.
So something like:
def __init__(...):
self.roles = dict()
self.affiliations = dict()
self.add_event_handler(""groupchat_presence"", self.muc_presence)
...
def muc_presence(self, presence):
nick = presence['muc']['nick']
self.roles[nick] = presence['muc']['role']
self.affiliations[nick] = presence['muc']['affiliation']
This is the general idea, you'll need to do some more work to make it handle nickname changes and people leaving the room properly.
I'm trying to teaching myself how to program by building programs/scrips that will be useful to me. I'm trying to retool a script I found online to send an email through gmail using a python script (Source).
This example has a portion of code to attach files, which I don't want/need. I have tweaked the code so that I don't have to attach any files, but when I do this I lose the body of the email. Any help/tips on how to modify the code to keep the body of the email intact?
Appreciate the help.
The sample code you're using creates a multi-part MIME message. Everything is an attachment, including the message body. If you just want to send a plain old single-part plain text or HTML message, you don't need any of the MIME stuff. It just adds complexity. See that bit in your sample's sendmail() call where it says msg.as_string()? Well, that just converts the MIME objects you've created to text. It's easy enough to specify the text yourself, if you are dealing with text to start with.
The function below is similar to code I used for mailing a log file in a script I wrote. It takes a plain text body and converts it to preformatted HTML (to work better in Outlook). If you want to keep it plain text, just take out the line that adds the HTML tags, and change the Content-Type header to "text/plain."
import smtplib
def sendmail(sender, recipient, subject, body, server="localhost"):
"Sends an e-mail to the specified recipient."
body = ("<html><head></head><body><pre>%s</pre></body></html>" %
body.replace("&", "&").replace("<", "<"))
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(server)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
I see you have a clue about what you did wrong.
In this case, the method attach() refers to adding something to the email. This is confusing because when we thing about attaching things and email, we think about adding extra files, not the body.
Based on some other examples, it seems that the attach method is used to add either text to the body or a file to the email.
So, to answer your question, the attach method does what you think it does and more--it also adds text to the body.
Welcome to SO, by the way. Smart choice picking Python for learning how to script.