Automating AutoHotkey Abbreviations And Autolaunch After An update

If you are as lazy as me and want the computer to do as much work as possible, then you must know AutoHotkey (AHK). AHK lets you write scripts and cool functions that make your computer do everything but mop your floor; actually, it just might.

Anyway, I use it to abbreviate words and phrases–especially critical when notetaking. I used to be an SADeaf Notetaker. In some ways, I still do, though my role has changed since late 2019. Nevertheless, I love AutoHotkey.

I use Google Sheets to map my abbreviations and formulas to output AHK-friendly code.

AutoHotkey is not all of the magic. We turn to Python. Rather than copying and pasting the new entries from column E into a .ahk file, then executing the .ahk script again, I run the following Python script from Sublime Text.

If you know Python and work with APIs, don’t forget to grab your own client_secret.json file! I have the file in the same folder as the .ahk script.

import os
import gspread
import pandas as pd
import csv

gc = gspread.oauth(credentials_filename='client_secret_XXXXX')
csv_file = 'weiyong_ahk_shorthand.csv'
shorthand_file = "weiyong_ahk_shorthand_python.ahk"

# Open the AHK definitions sheet
wks = gc.open("AutohotKey Definitions")
active_wks = wks.worksheet("for_python")
df = pd.DataFrame(active_wks.get_all_records())
df.to_csv("weiyong_ahk_shorthand.csv", index=False)

with open(shorthand_file, "w", encoding='utf-8') as my_output_file:
    with open(csv_file, "r", encoding='utf-8') as my_input_file:
        [ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
    my_output_file.close()

# Run the AHK script

os.startfile(f"{os.getcwd()}\\{shorthand_file}")
print(os.getcwd())

What does the script do? You ask.

This sheet “for_python” contains the entries for Python to import into the .ahk and execute.
  1. Authenticate my computer with Google using the gspread module
  2. Open a Google Sheet containing my AHK entries
  3. Copy all entries from the “for_python” sheet
  4. Paste it into weiyong_ahk_shorthand.csv
  5. From weiyong_ahk_shorthand.csv, iterate through the rows and generate a weiyong_ahk_shorthand_python.ahk file
  6. Launch weiyong_ahk_shorthand_python.ahk

I like that I do not need to manually copy and paste entries from the sheet into the ahk file and re-run it each time new abbreviations are appended.

Still, there is much room for improvement. I’d like to have the script:

  1. Compare the sheet and .ahk file. Then, only import new entries, and sort them alphabetically.
  2. Do nothing if there is no change or addition to the Google Sheet.

2 comments

Leave a comment

Your email address will not be published. Required fields are marked *