<M <Y
Y> M>

: Fisher-Price's My First Twitter Bot: On Sunday I wrote my first Twitter bot, with a bit of help from Leonard. (A Hacker School colleague inferred, understandably, that Leonard and I just write Twitter bots on the weekend, to relax.) Then yesterday I helped a peer get her first Twitter bot going, and decided to write it up for y'all/future Pythonistas.

Folks have already written other guides to writing good Twitter bots. Those more experienced people are better than I am at writing good, surprising bots, ones that respond to tiresome hashtags or argue with followers or what have you. My guide, in contrast, assumes that you already have some kind of code that spits out strings of 140 characters or fewer, and just want help interfacing with the Twitter API using Python so a Twitter account can say those tweets.

So!

  1. I rely on the python-twitter wrapper around the Twitter API. If you are using a virtual environment that you made with mkvirtualenv or similar, then activate your venv and

    pip install python-twitter

    If you live on the edge, or if you are a devil-may-care type who loves convenience so much more than safety that you tab-complete your passwords, then command-tab away from Snapchat* long enough to install the package globally:

    sudo pip install python-twitter

  2. EULA Hotel photo from Flickr, CC-BY-NC-SA, by Jeroen ElfferichNow, go to Twitter.com and create a Twitter account for your bot, e.g., @FreedomBot. Make sure that you give Twitter an email address whose messages you can actually read. Read the end user license agreement and agree to it. Did you know that there's a hotel in San Francisco named the Eula?

  3. Look for the automatic email from Twitter and follow the instructions to confirm your account. Once you've done that, go to dev.twitter.com and sign in with the username and password of your bot's Twitter account, e.g., your username is FreedomBot.
  4. Go to https://dev.twitter.com/apps and choose to create a new app. Yes, your "Markov chain parody of the Office of Management and Budget" script is an "app" for our purposes; this is the easiest way to get the relevant keys.
  5. Go ahead and fill in a reasonable name, description, and link (your website or Gitorious repo would do). These will not be publicly visible or scrutinized by Twitter's gatekeeper gnomes, so don't sweat it. Leave the "callback URL" field empty. Read the Rules of the Road (so much more folksy than "Guidelines for the Walled Garden") and agree.
  6. Now that you have an "app", go to the Settings tab and change your app type from Read-only to Read/Write, so you can actually post to Twitter from your script. (If you're having trouble navigating back to your app, go to dev.twitter.com/apps to find it.)
  7. Next, on your app's Details tab, click the button at the bottom to create your API secret key & token. It'll take a minute for Twitter to create those for you; after a minute, go ahead and refresh the page. Now that page gives you the "consumer key" and "consumer secret" as well as the API "access token key" and "access token secret".

    (The "consumer key/secret" pair identifies your "app" (the code you are writing) as something that is allowed to interact with the Twitter API; it's sort of a substitute for the User-Agent string in a browser. The "access token key/secret" pair authorizes the Twitter account whose tweets the "app" is gonna write. So conceivably you could write an app like Sycorax that lets your bot roleplay multiple accounts, and it would end up getting multiple access token key/secret pairs so that could work. This is all OAuth stuff that briefly turns you into an octopus when you understand it.)

  8. So, how can your script use these secret strings (to authenticate and authorize you) without those supersensitive nuclear launch codes falling into the wrong hands, viz., your GitHub repo? I did it this way:

    Open up a new file in the same directory as your bot script, called something like "twitterapi.py". Also add "twitterapi.py" to your repository's .gitignore.

    #!/wherever/you/put/python  # ok, probably /usr/bin/python
    
    import twitter
    
    api = twitter.Api(consumer_key="KEY",
    		  consumer_secret="SECRET",
                      access_token_key="KEY",
                      access_token_secret="SECRET")
    
  9. So now, in your application or in the Python interpreter, you can do:

    from twitterapi import api

  10. And then, to post your awesome string to Twitter as @FreedomBot:

    api.PostUpdate("wow\n so Program Assessment Rating Tool\nnice\n very budgetary")

  11. Optional step! If you want to leave your bot running to tweet at 5-minute intervals, then import time and stick a time.sleep(5*60) line and an api.PostUpdate(awesomestring) into a while True loop.
I am posting this guide on 5 December 2013, and undoubtedly Twitter will revamp all this within the next fortnight and switch to OAuth 2038 (OAuth For Workgroups) and turn their developer site into something you manipulate by holding up your mobile phone in front of your Google Glasses. But for right now this works.

* Is there a Snapchat desktop app? Maybe Snapchat is available for the iPad and in my hypothetical you're programming on your tablet? I don't know what people do these days.

Filed under:


: Narrator: On New Year's Day a few years ago, I went on a long train trip next to a white guy in his fifties who'd lived his whole life in South Carolina. As we talked, I got the strangest urge: I wanted to open my mouth and say, "When I was a kid --" but I had no idea how I'd finish that sentence, what anecdote or alien baseline I wanted to tell him about.

A week later, getting a haircut from an Astoria barber who'd emigrated from Italy at the age of 16 and never gone back, I had the same impulse. And it happened more and more often, more in conversations with strangers than with friends, and more with people younger than me than with my elders. I don't know why I got the impulse, or why it started waning, or whether it will go away.

Maybe it's maturity, or settling, or my dad's death and my mother's stories. Maybe it's that as I feel stronger, I find it easier to look back and not regret the paddling-about and flailing, my strange and circuitous paths to becoming who I became; I need to be OK with who I am in order to be OK with the past that made me. And maybe it's my increasing awareness that personal stories are important. Rules divide, narrative unites. If I don't tell you my stories, how will you know how different we are, and how we are the same?

I want to tell more stories. Share more of my story. At Hacker School I've entertained classmates with tales of software engineering before git, or how I met Leonard before the word "blog" -- those feel more like "when you were a kid," though. I want to finish that sentence that just hangs there like a stub.

Part of my story is that, when I was a kid, I was good at school. Sometimes this is useful. And, thanks to my family, I found writing pretty easy, and as early as elementary school busied myself with additional writing for school newspapers. That kind of skill, pumping out text for immediate informational consumption, became no big deal.

I was editor-in-chief of my junior high newspaper, then wrote and edited for my high school newspaper, then copyedited a tiny bit on my college newspaper. And it's just been scribble, scribble, scribble since then. If I limit myself to fairly journalisticish prose:

...just to start. And 4237 blog entries here since 10 December 2000, once I hit Publish on this one.

Twelve years ago, at my parents' request, I wrote an introduction to the Youth section of a community magazine. I thought about it today because a peer and I happily agreed that code we write today is far better than code we wrote in September, before Hacker School. I had written:

Like all writers, I often write things that seem great ... at the time. But, when I wince at my previous work, I try to remember that it's not the work that's changed; it's me. We're all growing and learning; a new perspective lets me see new sides (some of them unpleasant) of what I did before. I say to myself, "I could do that better now, if I did it again." And that means that my life between then and now has been worth it.

I hope that, years from now, when the children whose poems and stories and articles you're about to read are entering adulthood, they find some time to look back on their younger selves. They might even read the words in the following pages that they themselves wrote so long ago. And I hope that they will see, with surprise, how much they've grown, and take hope from that, because when we see that we have had reason to hope, that gives us reason to hope again.

(I don't love that prose, but how dismaying would it be if I did?)

High school journalism changed my life (to answer Jed). It gave me experience in spiral learning, interviewing, responsibility, and writing for a non-college-educated audience. Sometimes I was bullied by classmates. I dealt with praise and criticism of my work (yes, one needs to learn skills to deal with both). I had interdependencies and met deadlines to help my community.

Today I helped a colleague prep for a job interview by asking questions and helping reshape and translate the answers, finding stronger phrasings and themes. Finding the story. Maybe that's the most useful thing I got out of journalism: the skill of arranging facts in the shape of story. I don't want to write fiction; making things up only tickles my fancy if I can make people laugh. But I love understanding the world better by binding events together into a narrative, and then sharing it.

When I was a kid, I liked reading and telling stories. And I still do.


: Hacker School Gets an A on the Bechdel Test: When part of the joy of a place is that gender doesn't matter, it's hard to write about that joy, because calling attention to gender is the opposite of that. I want to illustrate this facet of my Hacker School experience: mostly, Hacker Schoolers of all genders talk about mostly the same things. And we talk about them in all gender combinations -- including, just by chance, among women.

The "Bechdel Test" asks whether a work of fiction includes at least two women with names who talk to each other about something other than a man. Thus in my blog I have an occasional series listing topics I've discussed with other women. My life passes the Bechdel Test! ;-)

So here is an list of some things I've discussed with Hacker School women. (About half the facilitators, cofounders, participants, and residents are women.)

Some Things Hacker School Women Talk About

I could make this list probably ten times longer. My point is, if you don't care about gender, Hacker School is awesome. If you're irritated by the tech industry's usual gender crap, Hacker School is blissfully free of it and you can -- if you want -- turn into someone who doesn't care about gender for three months.

You can apply now for the next batch -- apply by Saturday night, December 14th.

cross-posted to Geek Feminism with a cheesy sketch

Filed under:


: Giant Linkdump of Activism, Tech, And Silliness: Improving your project's hospitality. And Angela Byron on hospitality in "The story of my first DrupalCon". An October 26th tweet: "We only solve the problems that cause us pain. That's why design thinking starts with empathy."

As you think about end-of-year giving, consider the current matching initiative from OpenHatch? Your gift counts twice as much before 24 December. And you know many folks have already suggested that you give to The Ada Initiative (see my posts).

"Data & Society" is seeking its inaugural class of fellows.

Oh my gosh, Wikimedia Loves Monuments and Antarctica! And look at pretty resultant photos! Speaking of Wikimedia and freely licensed work, I'd love it if someone updated Dilip Singh Saund's info on the Wikimedia projects with the National Museum of American History's artifacts. Perhaps I shall look into that the next time I am in DC.

"Tooth."

Why repealing DOMA matters to someone in your community.

A short new aphorism from Mary Anne Mohanraj.

"Why I Will Never Return to the USA."

Maria Farrell on forms of exercise -- includes mention of a hypothetical fart!

I am a sucker for stories of artists who also study engineering: "The opening night film was Chittagong made by first time filmmaker Bedabrata Pain, who was a scientist at NASA before he decided to become a filmmaker. In fact, he has been inducted into the US Space Technology Hall of Fame for his inventions in digital imaging..."

"This Side, That Side: Restorying Partition (Yoda Press, 336 pages, Rs. 595) edited by Vishwajyoti Ghosh, is not intended to explain Partition to a global audience. It is a book written by and for South Asians." Sounds interesting.

"What do you do about the existential terror that being a woman is ultimately going to cut the legs from under your writing career?" Relatedly: the "Girl Scout" tax on women in the workplace.

An African-American sociologist writes: "I learned, watching my mother, that there was a price we had to pay to signal to gatekeepers that we were worthy of engaging. It meant dressing well and speaking well." If you've ever wondered why some poor people spend money on status symbols, or made assumptions about why poor people do that, read this.

"...I and other people at SFLC started posting on on patient forums, and we were attacked for being so insensitive and trying to fearmonger on those forums because 'we don’t know what it's like to have a device' and then's when I realised that I needed to talk about my own experience." Karen Sandler, on-it as always.

Empathy CAPTCHA - source code, FAQ and usage instructions.

Doing the rounds in several of my communities: James Mickens's hilarious columns.

An initiative to start more conversation around mental health and the tech industry.

I'm curious about Mozilla's interest in building a volunteer system administration team (mrz in 2012 and 2013). Interesting - they have a weekly BigBlueButton open meeting.

"This is how I have felt ever since."

A guide to really bad ideas - in Python.

Margo Seltzer, founder and CTO of Sleepycat Software and Harvard professor, talks about her career. Great video. I have been thinking about her recommendation to have three major endeavors simultaneously -- work, family/friends, and hobby -- for redundancy, so you rarely have everything in your life going to pieces at once!

"I am not an inferior programmer for applying three times. I did it despite being discouraged because I wanted to grow and that desire was stronger than any negative thoughts I had."

If you have ever wondered what the hell should actually go into setup.py, here's an incomplete but a helpful guide, here's a history of Python package management, and here's a guide to the future.

I'm very slowly working my way through an algorithms/data structures textbook whose language of instruction is Python.

I sort of fumbled around half-understanding Python decorators, then came across this explanation, which helped a lot.


: console.captain'slog: This week I started remembering JavaScript (two years ago I picked up a little bit). A few fun things:

  1. I understand @horse_js better now!
  2. I sort of understand the differences among Node, npm, ClojureScript, CoffeeScript, and random noun.js files.
  3. I paired with Tom, one of the facilitators, to port my Obama speech generator to JS. I can successfully write functions (including higher-order functions), randomly choose things using Math.random, make and use arrays and Objects, display things in a webpage, write for loops, get input from the user using prompt(), and put semicolons everywhere.
  4. The JSFiddle tutorial didn't mention a necessary step so I added it.
  5. The incrementation step in a JavaScript for loop keeps happening until the step when the run condition is no longer satisfied, so it's sort of more like a while loop? Anyway this tripped me up and gave me an off-by-one error until I grokked it.
  6. I'm glad Eloquent JavaScript is available online for free, and I'm glad that Node comes with a REPL. But, because I have been doing so much Python, it's natural for me to think that pretty basic things will work the same across lots of environments. And the textbook, as early as the first chapter, suggests doing things like print() and show() that give me stark errors in Node.
  7. Seriously, JavaScript, if I just try to add together a number and a string you might just try to make it work and give me something back? That does not strike me as the most logical choice.
    > 40+["yay", 23]
    '40yay,23'
    > 23+Object()
    '23[object Object]'
Thus, I have now watched "WAT" and enjoyed it. And I have made software put "Thank you, and may God bless NoSQL." on a webpage. So that's a good harvest.
Filed under:


(1) : JavaScript and How I Learn: From yesterday's JavaScript explorations:

"I have now discovered that element.innerText works in Chrome and in Epiphany but not in Firefox."

"This is why you use jQuery."

And now I do! My "presidential" "speech" generator is now a web page that calls upon a CSS file, jQuery, and my JavaScript to grab three buzzwords from the user, choose random items from some pre-written lists, interpolate everything appropriately into a text template, hide the input div, and display the letter to the user -- with a little footer that floats right. It's all "client-side", as the kids say.

Some more things I learned:

  1. Oh right, ordering matters. My <script> loading tags need to load up jquery.js before loading any JavaScript files that use jQuery functionality! Or else the web console says "wtf is '$'?" in more polite language ("ReferenceError: $ is not defined").
  2. I was wary of the whole event-handling paradigm but now I'm getting used to it and might like it. Instead of the default idea being "here I am, a script, doin' everything by myself, maybe shoehorn in some interactivity with the user sometimes", the default idea feels like "I'm a set of useful reactions to possible things the user will do".
  3. I know the windowshade-style hide and show jQuery functionality is a pretty clear "look! jQuery demo!" signal. And now I know why: because it is cool and easy and just works! Yay .hide()!
  4. To get the value of a text input: $( "#InputIDName" ).val();
    To stick a string into a div: $("#divName").html("string");
    I am pretty sure the ".html" method escapes things to keep you from opening up an XSS vuln but I'm not sure and need to check. Argh escaping!
I still want to fix up a bunch of user experience, but right now I've clearly achieved the goal of porting my toy from Python to JavaScript, so that makes me happy. My batch of Hacker School ended yesterday but I am keeping the momentum going (I got speech.js working this morning).

At Hacker School I followed my own advice and found or made up silly and boring and helpful projects to use while learning. My current rhythm seems to be: start by working through the first few chapters of a textbook to learn basic concepts and syntax, then think up a silly project to make and start making it, then run into problems one at a time, causing me to learn idioms and libraries and gotchas from a mix of my colleagues and the Internet. Maybe someday I will come back to chapter three of the book and engage in some more spiral learning! It's nice to have a diversified portfolio.

Filed under:


(2) : Why Julia Evans's Blog Is So Great: Some writing is persuasive; it aims to cause you to believe or do something. Some is expository; it aims to cause you to understand something. A lot of tech writing is persuasive or expository.

Some writing is narrative. It aims to cause you to feel or experience something. In personal narrative, the writer shares a personal experience and invites you to walk with her on that journey, experiencing it as she did, emerging with a new perspective. I really like narrative-style tech writing.

What I call the "Amazing Grace" story (previously) is, in a sense, all three of these. "Amazing grace! (how sweet the sound) / That sav'd a wretch like me! / I once was lost, but now am found, / Was blind, but now I see." Or, in more modern terms, "An English Sailor Found Salvation Through This One Weird Trick."

  1. Exposition: My experience started in sordid terror and ended in divine ecstasy
  2. Narration: Bask and wonder with me in the intricacy of my journey and the unexpected yet inevitable emergent properties of my condition
  3. Persuasion: Thus, if you are enthralled to sin, if you are a fallen resident of our fallen world, you should follow my example

I started thinking about this because my Hacker School colleague Julia Evans has a super-engaging blog. During our batch, she dove into operating system internals, and blogged about what she learned and how she learned it. She's consistently inspired me and made me laugh. Two of her fans (fellow HSers) even made a loving Markov-chain tribute, Ulia Ea.

One reason we love it is that most entries narrate her daily learning and illustrate a journey through confusion into wonder. See "Day 37: After 5 days, my OS doesn't crash when I press a key", which is possibly the most "Amazing Grace"-esque of her posts. Excerpt:

5. Press keys. Nothing happens. Hours pass. Realize interrupts are turned off and I need to turn them on....

12. THE OS IS STILL CRASHING WHEN I PRESS A KEY. This continues for 2 days....

As far as I can tell this is all totally normal and just how OS programming is. Or something. Hopefully by the end of the week I will get past "I can only receive one IRQ" and into "My interrupt handler is the bomb and I can totally write a keyboard driver now"....

I'm seriously amazed that operating systems exist and are available for free.

It's not just the large-scale rhetorical structure; her diction and even her punctuation delight me. I particularly marvelled at her sentences in "Day 43: SOMETHING IS ERASING MY PROGRAM WHILE IT’S RUNNING (oh wait oops)". Excerpt:

SURPRISE MY CODE IS NOT WORKING BECAUSE SOMETHING IS ERASING IT.

Can we talk about this?

  1. I have code
  2. I can compile my code
  3. Half of my binary gets overwritten with 0s at runtime. Why. What did I do to deserve this?
  4. No wonder the order I put the binary in matters.

It is a wonder that this code even runs, man. Man.

The disarmingly informal ALLCAPS adds to the intimacy more explicitly created with the question "Can we talk about this?" which invites the reader into one-on-one conversation. Moreover, I specifically call your attention to the statement "Why." and the repetition "man. Man." They demonstrate how Julia acknowledges mystery, with a tinge of disbelief.

As Patrick Nielsen Hayden observed,

A great deal of science fiction is about what the field's insiders often call "sense of wonder," a quality not entirely unrelated to the good old Romantic Sublime. Many of the genre's classics are in essence carefully-tuned machines designed to attract readers whose primary conscious loyalty is to rationalism, and lead them by a series of plausible contrivances to a sudden crescendo of mystical awe. This is an important part of SF from Olaf Stapledon to William Gibson and beyond.
And Julia Evans.

Filed under:


: Long Takes, Spit-Takes: A week ago, I saw the excellent Jeanne Dielman, 23 Quai du commerce, 1080 Bruxelles at the museum.

Akerman's singular avant-garde epic -- which surveys with unprecedented detail the mundane daily routine... Akerman creates a portrait of an enigmatic woman's inner life by focusing on her chores (cooking, cleaning, letter-writing)...
It is 201 minutes long. It's amazing, immersive. The main character does super-mundane things efficiently, and the first act feels like a graceful dance. Then we see her competence decrease on a frazzled day -- the first time she dropped something, I think I literally gasped. There's at least one single take in there that's seven minutes long; I think some are longer!

Then on Friday Leonard and I saw Children of Men at the museum, my third time and his first. Children of Men also has several very long takes, but they tend to include killings, mostly by gunfire. A lot of people die in this movie. I walked out shaken.

As I emerged into the lobby, I muttered, "That was pretty intense." And then a stranger said, "A little more exciting than Jeanne Dielman, huh?"

I laughed very hard.


: Darmok and Jalad at StackExchange: I have a cold, so I've been watching and reading comfort media. Yesterday Leonard and I rewatched that old Star Trek: The Next Generation episode "Cause and Effect". When the senior officers need to figure out what to do with the oracular number "three" that's popping up everywhere:

Riker: Maybe we should run a level-three diagnostic on all key systems.
LaForge: Good idea. And I'll have the computer run a pattern-matching algorithm based on the number three.

Luckily, right after that meeting, they have to deal with a giant space-time anomaly that renders those plans moot, so LaForge doesn't end up with an LCARS screen listing the billions of line numbers in the Enterprise's filesystem that correspond to mentions of the number three.

I know some subset of my cohort started drinking Earl Grey tea because Captain Picard did. I wonder how many technologists, solving problems and running meetings, reach for patterns we learned from Rick Berman et alia.

Filed under:


: Yuletide 2013 Recommendations: I have been sick with a cold for about a week. Fortunately, this year's Yuletide fan fiction harvest brought me tremendous bounty! I now feel the urge to re-watch or re-read Protector of the Small, Breaking Bad, Arrested Development, Brick, Stranger Than Fiction, Legally Blonde, and World War Z.

My bookmarks include:

Do you have any favorites from this year?
Filed under:



[Main]

You can hire me through Changeset Consulting.

Creative Commons License
This work by Sumana Harihareswara is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Permissions beyond the scope of this license may be available by emailing the author at sh@changeset.nyc.