check availability of meeting rooms in outlook with python - python-3.x

I am working on to write a python script to check if particular meeting room is available. If yes then meeting room will be booked, if not then python will find available time slot for that day.
For now, I have achieved to book meeting room but I am not able to check availability of rooms.
To book any meeting room, i have to send mail to that book meeting room configured mail id and corresponding acceptance/decline mail I receive as per the availability.
below is the snippet :
import win32com.client
import datetime
import pywintypes
oOutlook = win32com.client.Dispatch("Outlook.Application")
appt = oOutlook.CreateItem(1)
appt.Start = '2018-05-18 13:30'
appt.Subject = 'Follow Up Meeting'
appt.Duration = 30
appt.Location = '<name of meeting room>'
appt.MeetingStatus = 1
myRecipient = appt.Recipients.Add("<mail id of meeting room")
myRecipient.resolve
my_date = datetime.date(2018,5,18)
pywintypeDate = pywintypes.Time (my_date)
availabilityInfo = myRecipient.FreeBusy(pywintypeDate,30,True)
print(availabilityInfo)
# appt.Save()
# appt.Send()
# print("done")
output is :
000000000000000000000222222200222222022000000000000000000000000000000002222222222220000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000002220002222200000000000000000000000000000000002220022022222000000000000000000000000000000000000000000002222000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000222222200000000000000000000000000000000002220000022000000000000000000000000000000000000002220000222222000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000002220022022200000000000000000000000000000000000022000022000000000000000000000000000000000000000000000002222000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022000000000000000000000000000000000000000000000022022200000000000000000000000000000000002220002222000000000000000
so is it first byte (0) indicate time slot from 00:00 to 00:30 and soon for one complete month ?
Is it possible to get output only for one day ?
Do i have to parse the above output to check availability for my particular required time ?

appt.Recipients.Add returns the Recipient object. Resolve it first (Recipient.Resolve), then call Recipient.FreeBusy.

Related

how to change SL/TP with CCXT (python) on Binance Futures

How can I change the take profit or stop loss of an order already created via ccxt python in Binance futures?
I would like an already created order to be able to change the stop loss, as if I did it from the binance web cli, there is some way, I create my order like this
exchange.create_order(symbol=par, type='limit', side=side, price = precio, amount= monto, params={})
When detecting a certain pattern I would like to update the SL and TP, it's possible?
I have not found information in the ccxt wiki
There is an edit_order function that you may want to try.
import ccxt
exchange = ccxt.binanceusdm()
exchange.apiKey = 'YOUR_API_KEY'
exchange.secret = 'YOUR_API_SECRET'
symbol = 'BTC/USDT'
order_id = 'ORDER_ID'
order_type = 'limit'
side = 'buy'
amount = 0.001
price = 16000
stop_loss = 15000
take_profit = 17000
exchange.edit_order(order_id, symbol, order_type, side, amount, price, {'stopLossPrice': stop_loss, 'takeProfitPrice': take_profit})

wrote a code for post notifications on teams when i got mail. when run while loop it continuously post notification until minute end

import pymsteams
import win32com.client as client
from datetime import datetime, timedelta
import pywintypes
import time
def outlookFind():
outlook = client.Dispatch("Outlook.Application")
namespace=outlook.GetNamespace("MAPI")
inbox = namespace.GetDefaultfolder(6)
messages = inbox.Items
received_datime = datetime.now()- timedelta(seconds=30)
# print(received_datime)
received_datime = received_datime.strftime('%m/%d/%Y %H:%M:%S %p')
# print(received_datime)
messages = messages.Restrict("[ReceivedTime] >= '" + received_datime + "'")
messages = messages.Restrict("[SenderEmailAddress] = 'contact#mail'")
messages = messages.Restrict("[Subject] = 'Long Running WEBService!'")
for message in messages:
if message:
myTeamsMessage = pymsteams.connectorcard("webhook for teams channel")
myTeamsMessage.text("You got a new mail with subject name Long Running WEBService!")
myTeamsMessage.send()
if __name__=="__main__" :
while True:
outlookFind()
This is the code i wrote for post notifications in teams when i got a mail in outlook. when i run this its post continuous notifications until th next minut starts. i want to post one notification for one mail.
i run this code in background using pythonw.exe

pandas aggregation based on timestamp threshold

I hope somebody can help me to solve this issue.
I have a csv file structured as follow:
I am trying to group the events based on message, name, userID if the events manifests in a 10min threshold starting from the first event matched.
the output I am expecting from the csv, is to see only 3 rows, because the second and third (as they are in 10min threshold and the message and name and ID are the same, they should be grouped) and have an extra columns name event_count that report how many time that event occurred.like this
I start working on this and my script looks like this:
import csv
import pandas as pd
# 0. sort data by timestamp if not already sorted
file_csv = 'test.csv'
f = pd.read_csv(file_csv)
f['#timestamp'] = pd.to_datetime(f['#timestamp'])
f = f.sort_values('#timestamp')
# lazy groupby
groups = f.groupby(['message','name','userID'])
# 1. compute the time differences `timediff` and compare to threshold
f['timediff'] = groups['#timestamp'].diff() < pd.Timedelta(minutes=10)
# 2. find the blocks with cumsum
f['event_count'] = groups['timediff'].cumsum()
# 3. groupby the blocks
out = (f.groupby(['message','name', 'userID'])
.agg({'#timestamp':'first', 'timediff':'count'})
)
keep_col = ['#timestamp', 'message', 'name', 'userID', 'event_count']
new_f = f[keep_col]
new_f.to_csv("aggregationtest.csv", index=False)
But the aggregation is totally wrong because is grouping all the event together even if they don't fall in the 10min threshold.
I am really struggling to understand what I am doing wrong if somebody can help me to understand the issue
UPDATE:
After some testing I managed to get a closer output to what I am expecting but still wrong.
I did some updated on the out variable as follow
out = (f.groupby(['message','name', 'userID', 'timediff']).agg({'#timestamp':'first','message': 'unique','name': 'unique', 'userID': 'unique', 'timediff': 'count'}))
This bit of code now produce an output that looks like:
But even if its grouping now, the count is wrong. Having this csv file
#timestamp,message,name,userID
2021-07-13 21:36:18,Failed to download file,Failed to download file,admin
2021-07-14 03:46:16,Successful Logon for user "user1",Logon Attempt,1
2021-07-14 03:51:16,Successful Logon for user "user1",Logon Attempt,1
2021-07-14 03:54:16,Successful Logon for user "user1",Logon Attempt,1
2021-07-14 04:55:16,Successful Logon for user "user1",Logon Attempt,1
I am expecting to have the following event_count
1
3
1
But I am getting different out come.
You'll have to somehow identify the different periods within the groups. The solution below gives each period within the group a name, which can then be included in the groupby that generates the count:
import pandas as pd
file_csv = 'test.csv'
f = pd.read_csv(file_csv)
f['#timestamp'] = pd.to_datetime(f['#timestamp'])
f = f.sort_values('#timestamp')
def check(item): #taken from https://stackoverflow.com/a/53189777/11380795
diffs = item - item.shift()
laps = diffs > pd.Timedelta('10 min')
periods = laps.cumsum().apply(lambda x: 'period_{}'.format(x+1))
return periods
#create period names
f['period'] = f.groupby(['message','name','userID'])['#timestamp'].transform(check)
#groupby and count
(f.groupby(['message','name', 'userID', 'period']).agg({'#timestamp':'first', 'period': 'count'})).rename(columns={"period": "timediff"}).reset_index()
Output:
message
name
userID
period
#timestamp
timediff
0
Failed to download file
Failed to download file
admin
period_1
2021-07-13 21:36:18
1
1
Successful Logon for user "user1"
Logon Attempt
1
period_1
2021-07-14 03:46:16
3
2
Successful Logon for user "user1"
Logon Attempt
1
period_2
2021-07-14 04:55:16
1

How to check if an email is part of a conversation?

Our company has a Customer Service (CS) process where after a client reports an error with our software, we'll get an email about their complain with generic subject ("User Submitted Error") and short description of the error. We then fix the problem and email back to client. An issue may have 1, or multiple emails back and forth between our CS department and client.
My python scrip used win32com module to pull emails from Outlook and put them into dataframe, each row as an entry for a unique reported error. After reading (https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.conversationid), I decided to go with message.ConversationID. However, the generic email subject means sometimes they would group all unrelated emails together, make ConversationID not really that unique nor useful to me.
Can someone provide me some guide on how best to tackle this issue?
outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI')
def message_to_row(message, year, start_month, end_month): # Process each email into row of information
message_time = message.ReceivedTime
winrec_time = message.ReceivedTime
rec_time = pywintypes.Time(winrec_time)
rec_year = rec_time.year
rec_month = rec_time.month
rec_day = rec_time.day
rec_time_string = str(rec_time.hour) + ":" + str(rec_time.minute)
rec_time = format(datetime.datetime.strptime(rec_time_string, "%H:%M"), "%H:%M")
if rec_year >= year:
if rec_month in range(start_month, end_month):
convo_id = message.ConversationID
message_body = message.body.replace("_", " ")
row = [convo_id, rec_year, rec_month,
rec_day, rec_time, message_body]
return row

How to call a function every interval time Odoo 11

i know we can create automatic action using cron in odoo
but I want something a different
in the mass mailing of odoo i want to add a repetion option of mail mass mailings
Example in the Form view_mail_mass_mailing_form > Options page
I added a repetition selection field,
I added this because I want each mass mail alone
class MailMassMailing(models.Model):
_inherit = 'mail.mass_mailing'
recurrence_mail = fields.Selection([
('daily', 'Day'),
('weekly', 'Weeks'),
('monthly', 'Months'),
], string='Recurring')
I want this mass mailng to send each (days or weeks or months)
how to call a function with interval date,
how to call a function every (days or weeks or months)
The sending of this mass mailing is revived from the date of creation
Just extend Mass Mailing model with a new date field and implement a model method to use for a daily running ir.cron.
from odoo import api, fields, models
class MailMassMailing(models.Model):
_inherit = 'mail.mass_mailing'
recurrence_mail = fields.Selection([
('daily', 'Day'),
('weekly', 'Weeks'),
('monthly', 'Months'),
], string='Recurring')
last_sent_on = fields.Date()
#api.model
def run_send_recurring(self):
""" Resend mass mailing with recurring interval"""
domain = [('recurrence_mail', '!=', False)]
# TODO monthly should be solved in another way, but that
# is not needed for this example
deltas = {'daily': 1, 'weekly': 7, 'monthly': 30}
today = fields.Date.today()
for mass_mail in self.search(domain):
# never sent? go send it
if not mass_mail.last_sent_on:
# send the way you want
# or get delta between today and last_sent_on
last_dt = fields.Date.from_string(mass_mail.last_sent_on)
if (today - last_dt).days >= deltas[mass_mail.recurrence_mail]:
# send the way you want
Thank you #CZoellner for your help
I found the solution with your idea
# Solution ############### .py
#api.model
def run_send_recurring(self):
""" Resend mass mailing with recurring interval"""
date_format = '%Y-%m-%d'
domain = [('recurrence_mail', '!=', False),('state','=','done')]
deltas = {'daily': 1, 'weekly': 7, 'monthly': 30}
logger.info("______deltas________: %s ",deltas)
today = fields.Date.today()
logger.info("______today________: %s ",today)
for mass_mail in self.search(domain):
logger.info("______mass_mail________: %s ",mass_mail)
# never sent? go send it
if not mass_mail.last_sent_on:
self.put_in_queue()
joining_date = mass_mail.last_sent_on
current_date = (datetime.today()).strftime(date_format)
print('joining_date',joining_date)
d1 = datetime.strptime(joining_date, date_format).date()
logger.info("______1 day________: %s ",d1)
d2 = datetime.strptime(current_date, date_format).date()
logger.info("______2 day________: %s ",d2)
logger.info("______deltas[mass_mail.recurrence_mail]________: %s ",deltas[mass_mail.recurrence_mail])
r = relativedelta(d1,d2)
logger.info("______r day________: %s ",r.days)
if (r ,'>=' , deltas[mass_mail.recurrence_mail]):
mass_mail.put_in_queue()

Resources